2016-03-12-enumerable-shortcuts.md 600 B


title: Enumerable Shortcuts

categories: bits

You can call a method on every item of an enumerable like

[1, 2, 3].each { |num| num.to_s }

Which can be further reduced to:

[1, 2, 3].each(&:to_s)

Unfortunately this method doesn't work if you want to achieve something like

%w[hi how are you].each { |word| puts word }

Instead, you would have to use something like:

%w[hi how are you].each(&method(:puts))

Beware that parenthesis are required around :puts. Also, this only works if each element is passed as the given method's argument.