Ruby Enumerable Cheat Sheet
The Enumerable Module is a bunch of methods that work
with collections such as Arrays, Hashes and Ranges. Here are some of our favorite
methods!
map
Map returns a new array after performing a block operation on each of
the elements in the collection. Map is like a transformation method.
It applies your block of code to the collection transforming it!
(1..4).map {|x| x+1}
#=> [2,3,4,5]
to_a
Returns an array based on the argument passed into
it. For example, if you pass in a range (1..7) it will return an array of the
numbers 1 through 7. Calling to_a on a hash will return nested arrays with 2 items each (the key, and the value)
(1..7).to_a
#=> [1,2,3,4,5,6,7]
{ 'a'=>1, 'b'=>2, 'c'=>3 }.to_a
#=> [["a", 1], ["b", 2], ["c", 3]]
each_with_object
Iterates each element passed through a block with the arbitrary object
passed first. This is useful for modifying hashes.
%w(gnidoC si nuf).each_with_object({}) { |str, hsh| hsh[str] = str.reverse }
# => {'gnidoC' => 'Coding', 'si' => 'is', 'nuf' => 'fun'}
include?
Returns true if any member of enum equals obj. Equality is tested using ==.
Checks if a collection "includes" the item passed in as an argument.
array = [1,2,3,4]
array.include?(4)
#=> true
each_slice
Breaks collection into a group of n sized elements. Useful to transform
an array into an array of sub arrays for modifications.
(1..9).each_slice(3) { |x| print x }
#=> [1, 2, 3][4, 5, 6][7, 8, 9]
grep
Returns an array of every element in enum for which
Pattern === element. If the optional block is supplied,
each matching element is passed to it, and the block’s
result is stored in the output array. In short, grep finds and
returns all things matching the argument.
["Test", "Foo", "Bar"].grep 'Foo'
#=> ["Foo"]
inject
Easily allows users to add, multiply, subtract through each element of a collection.
(1..5).inject { |sum, element| sum + element }
#=>15