2014-11-21 72 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因此獲得空的參數列表。