2014-11-21 68 views
1

意味着关于Ruby的语法问题:是什么:upcase在Ruby中

p = lambda &:upcase 
p.call('a') ## A 

为什么它是有效的? 'upcase'从哪里来?
我认为没有一个参数应该发送到upcase,为什么这个proc可以有一个参数的bug?

回答

1

第一个参数是接收器。

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因此获得空的参数列表。