ruby中to_proc方法

来源:互联网 发布:ppty聚力网络电视 编辑:程序博客网 时间:2024/06/05 03:22
## case 1class Symbol  def to_proc    proc { |x| x.send(self) }  endendp [1, 2, 3].map &:to_sp [1, 2, 3].map &proc { |x| x*x }puts "*" * 50
## case 2class 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}"  endendp [1, 2, 3].map &ProcStore.new(:hi)p [1, 2, 3].map &ProcStore.new(:hello)puts "*" * 50
## case 3def test x  "test #{x}"endp [1, 2, 3].map &method(:test)

map中&后调用to_proc方法