Ruby's Sleek Looping Idioms Made Compact
Ruby's looping idioms are sleek & compact. Use `map` with block arguments for concise code: `[1, 2].map(&:to_s) #=> ["1", "2"]`.
Ruby has some of the sleekest looping idioms in all of coding, and with some idiomatic sugar, you can make them even more compact.
TL;DR - numbered block arguments are pretty good.
1. Call some method on each element
[1, 2].map(&:to_s) #=> ["1", "2"]
[1, 2].map { _1.to_s } #=> ["1", "2"]
2. Call some method with each element as the argument
def greet(object, volume)
"Hi, #{object}, #{volume}"
end
guests = [[1, :loudly], [2, :quietly]]
guests.map { |args| greet(*args) }
#=> ["Hi, 1, loudly", "Hi, 2, quietly"]
guests.map { greet(_1, _2) }
#=> ["...