什么&:upcase在Ruby中的意思
关于Ruby的语法问题:
p = lambda &:upcase p.call('a') ## A
为什么它有效? 这个”upcase’来自哪里?
我认为没有一个参数应该发送到upcase
,bug为什么这个proc可以有一个参数?
第一个参数是接收器。
lambda(&:upcase)
是一个简写
lambda { |x| x.upcase }
就像
lambda(&:+)
是一个简写
lambda { |x, y| x.+(y) }
更准确地说,参数中的&x
将调用x.to_proc
; Symbol#to_proc
碰巧返回上述内容。 例如,这是来自Rubinius源的Symbol#to_proc
的定义:
class Symbol # Returns a Proc object which respond to the given method by sym. def to_proc # Put sym in the outer enclosure so that this proc can be instance_eval'd. # If we used self in the block and the block is passed to instance_eval, then # self becomes the object instance_eval was called on. So to get around this, # we leave the symbol in sym and use it in the block. # sym = self Proc.new do |*args, &b| raise ArgumentError, "no receiver given" if args.empty? args.shift.__send__(sym, *args, &b) end end end
正如您所看到的,生成的Proc
将从第一个参数移开以充当接收器,并传递其余参数。 因此, "a"
是接收器,因此"a".upcase
获得空参数列表。