問題:
Possible Duplicate:可能的重複:
What does map(&:name) mean in Ruby? map(&:name) 在 Ruby 中是什麼意思?
In Ruby, I know that if I do:在 Ruby 中,我知道如果我這樣做:
some_objects.each(&:foo)
It's the same as它與
some_objects.each { |obj| obj.foo }
That is, &:foo
creates the block { |obj| obj.foo }
也就是說, &:foo
創建塊{ |obj| obj.foo }
{ |obj| obj.foo }
, turns it into a Proc, and passes it to each. { |obj| obj.foo }
,將其轉換爲 Proc,並將其傳遞給每個。 Why does this work?爲什麼這樣做? Is it just a Ruby special case, or is there reason why this works as it does?它只是一個 Ruby 特例,還是有理由這樣工作?
解決方案:
參考一: https://stackoom.com/question/8E9W參考二: Ruby ampersand colon shortcut [duplicate]