1
意味着关于Ruby的语法问题:是什么:upcase在Ruby中
p = lambda &:upcase
p.call('a') ## A
为什么它是有效的? 'upcase'从哪里来?
我认为没有一个参数应该发送到upcase
,为什么这个proc可以有一个参数的bug?
意味着关于Ruby的语法问题:是什么:upcase在Ruby中
p = lambda &:upcase
p.call('a') ## A
为什么它是有效的? 'upcase'从哪里来?
我认为没有一个参数应该发送到upcase
,为什么这个proc可以有一个参数的bug?
第一个参数是接收器。
lambda(&:upcase)
就像
lambda(&:+)
为
lambda { |x| x.upcase }
速记是在论据
lambda { |x, y| x.+(y) }
更正确,&x
速记会叫x.to_proc
; Symbol#to_proc
恰好返回上面。例如,这是从Symbol#to_proc
Rubinius的源定义:
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
因此获得空的参数列表。