Ruby符号到#proc with puts

时间:2014-12-15 22:07:04

标签: ruby function

我正在学习红宝石2周,但我现在可能有问题了

words = ["hello", "world", "test"] 
words.map do |word|
     word.upcase
end

等于

words = ["hello", "world", "test"] 
words.map(&:upcase)

但为什么呢

m = method(:puts)
words.map(&m)

工作??

2 个答案:

答案 0 :(得分:2)

Object#method从给定符号中获取Method个对象。 method(:puts)获取与Kernel#puts对应的Method对象。

一元&运算符调用引擎盖下的to_proc

method(:puts).respond_to?(:to_proc) # => true
to_proc中的

Method会返回与Proc相当的{ |x| method_name(x) }

[1, 2, 3].map &method(:String)  # => ["1", "2", "3"]
[1, 2, 3].map { |x| String(x) } # => ["1", "2", "3"]

答案 1 :(得分:1)

您正在使用Object#method将该方法从内核中拉出并将其存储在变量" m"。

&操作员调用Method#to_proc。明确说明所有这些:

irb(main):009:0> m = Kernel.method(:puts); ["hello", "world", "test"].map{|word| m.to_proc.call(word)}
hello
world
test
=> [nil, nil, nil]