Reputation: 118299
Confusion with Array#each
as below:
%w{ david black }.each {|str| str.capitalize }
#=> ["david", "black"]
The above code is cool,but how the below logic works,couldn't understand.
%w{ david black }.each(&:capitalize)
#=> ["david", "black"]
Upvotes: 1
Views: 79
Reputation: 230531
It's a very old trick, called Symbol#to_proc
.
You can read more about it here: http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html
Basically, it's a shortcut for calling methods that take no args. Often used in map
, for example.
%w[i can measure length of strings].map(&:length) # => [1, 3, 7, 6, 2, 7]
Upvotes: 3
Reputation: 3355
The notation of &:something
does for every element of the array the method something
.
This is usually used with map to change every entry of the array or to extract data from hashes.
[{:foo => :bar, :meh => :bar2}, {:foo => :one, :meh => :two}].map(&:foo)
=> [:bar, :one]
Upvotes: 0
Reputation: 3317
I don't get your example with .each, maybe you meant .map
When you pass in the &:method_name it's shorthand for doing it in the block. So for each item apply this method.
Upvotes: -1
Reputation: 127
How about using map?
[1173]pry(main)> ["david","black"].map{|str| str.capitalize }
=> ["David","Black"]
[1173]pry(main)>
Upvotes: 0