Alan Coromano Alan Coromano - 4 years ago 87
Ruby Question

Omitting an argument for a method in a block

I wonder, is it possible to do something similar in Ruby to what I can do in Scala or other languages:

someCollection.foreach(x => println(x)) // a full version
someCollection.foreach(println) // a short version

In Ruby I can do:

some_array.each { |x| puts x }

So how can I do this?

some_array.each { puts }


I'm not talking about puts in particular, it just picked it for example. There might be
which takes one parameter. { some_other_method } # ???

def some_other_method a
# ... doing something with a

Answer Source

If you look up the rules for implicit η-expansion in the SLS (§6.26.5), it should be immediately obvious that it relies crucially on static type information and thus cannot possibly work in Ruby.

You can, however, explicitly obtain a Method object via reflection. Method objects respond to to_proc and like any object that responds to to_proc can thus be passed as if they were blocks using the unary prefix & operator:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download