Show Menu
Cheatography

Ruby Enumerable Quick Ref Cheat Sheet by

Sorting

partition: 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

revers­e_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_slice 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]
unshift 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 # => []
compact 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

delete_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_ke­y?(key) Returns true if the given key is present in hsh.
h.has_­key­?("a­")     # => true
has_va­lue­?(v­alue) 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 }
       
 

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
          vim-rails Cheat Sheet
            Ruby on Rails Cheat Sheet by Dave Child and addedbytes.com