Iterators and Blocks
The each method is Ruby's most used iterator. It takes a block โ a chunk of code you pass to a method. Blocks come in two flavors: curly braces for single-line, and do...end for multi-line.
[1, 2, 3].each { |num| puts num }
["a", "b"].each do |letter|
puts letter
end
You can use yield inside a method to call a block that was passed to it:
def greet
puts "Hello!"
yield
puts "Goodbye!"
end
greet { puts "How are you?" }
map transforms every element and returns a new array. select keeps elements where the block returns true. reject is the opposite.
[1, 2, 3].map { |n| n ** 2 } # => [1, 4, 9]
[1, 2, 3].select { |n| n.odd? } # => [1, 3]
[1, 2, 3].reject { |n| n.odd? } # => [2]
reduce (also called inject) folds an array down to a single value by accumulating results:
[1, 2, 3, 4].reduce(0) { |sum, n| sum + n } # => 10
[1, 2, 3, 4].reduce(:+) # => 10
each_with_index and each_with_object give you more control when iterating:
["a", "b"].each_with_index { |val, i| puts "#{i}: #{val}" }
[1, 2].each_with_object([]) { |n, arr| arr << n * 10 } # => [10, 20]
Try it Yourself ->