&是一个关键字,不是代码,常在下面的代码中出现
#命名代码块
def hi &block
block.call
end
hi{9} #=>9
#迭代中的简写形式
a = [1,2,3]
a.map{ |x| x.to_s } #["1","2","3"]
a.map(&:to_s) #["1","2","3"]
解释a.map(&:to_s)代码执行
#map接受的是一个代码块
a.map{ |x| x.to_s } #类似这种形式
#&:to_s
"&"+":symbol"的形式,其实是将:symbol调用to_proc方法,将整个(&:to_s)转化成为一个代码块
#symbol具备to_proc方法
Symbol.instance_methods.grep(/to_proc/) #=> to_proc
#&+proc对象效果一样,因为proc对象也响应to_proc方法
a.map(&proc{|x| x.to_s}) #["1","2","3"]
#自己定义symbol中的proc方法
class Symbol
def to_proc
proc { |x| x.send(self) }
end
end
p [1, 2, 3].map &:to_s
#代码示例,进行自定义迭代
class ProcStore
def initialize handler
@handler = handler
end
def to_proc
proc { |ele| send(@handler, ele) }
end
def hi ele
"hi #{ele}"
end
def hello ele
"hello #{ele}"
end
end
p [1, 2, 3].map &ProcStore.new(:hi) #["hi 1", "hi 2", "hi 3"]
p [1, 2, 3].map &ProcStore.new(:hello)
#代码示例,Method对象也响应to_proc方法
def test x
"test #{x}"
end
p [1, 2, 3].map &method(:test) #["test 1", "test 2", "test 3"]