Show Menu

Ruby Enumerable Quick Ref Cheat Sheet by

rails     ruby     rubyonrails

Sorting

part­ition: Returns two arrays, the first containing the elements which the block evaluates to true, the second containing the rest.
(1..6).pa­rtition { |v| v.even? }     # => [[2, 4, 6], [1, 3, 5]]
sort­_by: Returns array sorted by the return value of the block.
[apple pear fig].s­ort_by {|word| word.l­ength}     # => [fig, pear, apple]
max and min: Returns max/min element based on sorting by { |a, b| a <=> b }
[fish dog horse].max { |a, b| a.length <=> b.length }     # => "horse"
[fish dog horse].max(2) {|a, b| a.length <=> b.length     # => [horse, fish]
max_by and min_by: Returns element with max/min block return value
[fish dog horse].max_by { |x| x.length }     # => "horse"
[fish dog horse].ma­x_by(2) {|x| x.length }     # => [horse, fish]

Searching

select and select! Returns array of all elements where block returns true
[1,2,3­,4,­5].s­elect { |num| num.even? }     # => [2, 4]
reject and reject! Returns array of all elements where block returns FALSE **
[1, 2, 3, 4, 5].reject { |num| num.even? }     # => [1, 3, 5]
grep: without block
[1, 'a', 2, 'b'].g­rep­(In­teger)     # => [1,2]
[dog cat tree doggie­].g­rep­(/dog/)    # => [dog, doggie]
grep: With Block
['a', 1, 2, 'b'].g­rep­(St­ring, &:­upcase) # find strings & upcase    ­#=> [A, B]
index: Returns the index of the first object == to value
[ "­a", "­b", "­c" ]index­("b")     # => 1

Iterators

reve­rse­_each Same as each but in reverse
[dog cat abc].r­eve­rse­_each { |word| str += "­#{word} " }   ­=> abc cat dog
each­_cons Iterates the given block for each array of consec­utive elements.
(1..10­).e­ach­_co­ns(3) { |a| p a }
#outputs:
[1, 2, 3]
[2, 3, 4]
[3, 4, 5] #etc...
each­_sl­ice terates the given block for each slice of elements.
(1..10­).e­ach­_sl­ice(3) { |a| p a }{
# outputs below
[1, 2, 3]
[4, 5, 6]
[7, 8, 9] #etc...
cycle repeats contents
["a", "­b", "­c"].c­ycle { |x| puts x } # print, a, b, c, a, b, c,.. forever.
["a", "­b", "­c"].c­yc­le(2) { |x| puts x } # print, a, b, c, a, b, c.
 

Misc

sample Chose a random element or n random elements from array
[1,2,3­,4,­5,6­].s­amp­le(3) # => [5, 6, 2]
unsh­ift Add to front of array
[2,3,4­].u­nsh­ift(1) # => [1, 2, 3, 4]
shift deletes first item from arr
[1, 2, 3, 4, 5].shift # => [2, 3, 4, 5]
pop remove the last x items
[1, 2, 3, 4, 5].pop(2) # => [4, 5]
delete delets item passed
[2, 3, 4, 8].del­ete(8) # => [2, 3, 4]
clear Remove all elements from array
[2,3,4­].clear # => []
comp­act remove nils from array
[2,3,n­il,4, nil, 8, nil].c­ompact # => [2, 3, 4, 8]
uniq removes duplicates from arr
[1, 2, 3, 4, 5, 1, 2].uniq # => [1, 2, 3, 4, 5]
reduce or inject: Iterate over a collection of data and perform proc/block
(5..10­).r­edu­ce(:+) # => 45
longest = [cat sheep bear].i­nject do |memo, word|
  memo.length > word.l­ength ? memo : word
end
longest # => "­she­ep"

Hash Methods

dele­te_if / keep_if Delete­s/keeps every key-value pair from hsh for which block evaluates to true.
h.dele­te_if {|key, value| key >= "­b" }     # => {"a"=­>100}
has_­key­?(k­ey) Returns true if the given key is present in hsh.
h.has_­key­?("a­")     # => true
has_­val­ue?­(va­lue) Returns true if the given value is present in hsh.
h.has_­val­ue?­(200)     # => true
invert Returns a new hash created by using hsh's values as keys, and the keys as values.
h.invert     # => {100=>­"­a", 200=>"b­", 300=>"c­"}
reject / reject! Same as Hash#d­ele­te_if, but works on (and returns) a copy of the hsh. Equivalent to hsh.du­p.d­ele­te_if.
h.reject {|key, value| key >= "­b" }     # => {"a"=­>100, "­c"=>300}
select /select! Returns a new hash consisting of entries for which the block returns true.
h.select {|k,v| k > "­a"}     # => {"b" => 200, "­c" => 300}
Examples above use h = { "­a" => 100, "­b" => 200, "­c" => 300 }

Download the Ruby Enumerable Quick Ref Cheat Sheet

2 Pages
//media.cheatography.com/storage/thumb/dwapi_ruby-enumerable-quick-ref.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Rails 4 Cheat Sheet
            Ruby on Rails Cheat Sheet by Dave Child and addedbytes.com