简体   繁体   中英

Confusion with `Array#each` in Ruby

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"]

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]

How about using map?

[1173]pry(main)> ["david","black"].map{|str| str.capitalize }
=> ["David","Black"]
[1173]pry(main)>

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM