简体   繁体   English

将方法传递给Ruby中的Proc

[英]Passing a method to Proc in Ruby

In Ruby symbol can be conveniently converted to a Proc such as: 在Ruby中,符号可以方便地转换为Proc,例如:

%{john terry fiona}.map(&:capitalize)   # -> %{John Terry Fiona}

Is there a way to pass a method to a Proc, to shorten the following code: 有没有办法将方法传递给Proc,以缩短以下代码:

["john", "terry", "fiona"].each do |n|
  assert n.valid_encoding?
end

Thanks. 谢谢。

%w{john terry fiona}.map(&:valid_encoding?).each(&method(:assert))

Unorthodox approach to the same thing: 对于同样的事情的非正统方法:

Compose = 
  lambda do |*xs|
    ph, *ps = xs.map(&:to_proc)
    lambda do |*ys|
      r = ph[*ys]
      ps.each do |p|
        r = p[r]
      end
      r
    end
  end

["john", "terry", "fiona"].each(&Compose[:valid_encoding?, method(:assert)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM