Apply method to each elements in array/enumerable
It's worth noting that if you have an array of objects you want to pass individually into a method with a different caller, like this:
# erb<% strings = %w{ cat dog mouse rabbit } %><% strings.each do |string| %> <%= t string %><% end %>
You can use the method
method combined with block expansion behavior to simplify:
<%= strings.map(&method(:t)).join(' ') %>
If you're not familiar, what method
does is encapsulates the method associated with the symbol passed to it in a Proc and returns it. The ampersand expands this Proc into a block, which gets passed to map
quite nicely. The return of map
is an array, and we probably want to format it a little more nicely, hence the join
.
The caveat is that, like with Symbol#to_proc
, you cannot pass arguments to the helper method.