#each with index
The #each_with_index method calls a block with two arguments: the item and the index.
hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
#inject
The #inject method combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
def sum(array)
array.inject(0) do |sum, i|
sum += i
end
end
sum([1,2,3])
#=> 6
#select
The #select method invokes the block passing in successive elements from self, returning an array containing those elements for which the block returns a true value.
all_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
all_numbers.each do |number|
even_numbers << number if number%2 == 0
end
#=> [2, 4, 6, 8, 10]
#reverse
The #reverse method reverses self in place.
a = [ "a", "b", "c" ]
a.reverse! #=> ["c", "b", "a"]
a #=> ["c", "b", "a"]