简体   繁体   中英

Passing a method to Proc in Ruby

In Ruby symbol can be conveniently converted to a Proc such as:

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

Is there a way to pass a method to a Proc, to shorten the following code:

["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)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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