Eunice Choi
Web Development Student | Dev BootCamp SF

Projects I've Worked On


Soon To Come


Ruby Enumerables Cheat Sheet



Method Example
map

returns a new array after performing a block operation on each of the elements in the collection

(1..4).map {|x| x+1}
#=> [2,3,4,5]
to_a

Returns an array based on the argument passed into it

(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

Calls block once for each element in self, passing that element as a parameter

a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }

#=> a -- b -- c --
each_with_index

Yields all elements with their indices

hash = Hash.new
%w(cat dog wombat).each_with_index{
|item, index|
hash[item] = index
}

hash
#=> {"cat"=>0, "dog"=>1, "wombat"=>2}
each_slice

Breaks collection into a group of n sized elements

(1..9).each_slice(3) { |x| print x }
#=> [1, 2, 3][4, 5, 6][7, 8, 9]
include?(value)

Returns true if any member of enum equals object

array = [1,2,3,4] array.include?(4)
#=> true
sort

Returns array sorted by <=> operator or by block

a = [ "d", "a", "e", "c", "b" ]
a.sort
#=> ["a", "b", "c", "d", "e"]

a.sort {|x,y| y <=> x }
#=> ["e", "d", "c", "b", "a"]
grep

Returns an array of every element in enum for which Pattern === element

["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