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 }


UPDATE:

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

some_array.map { some_other_method }
some_array.map(some_other_method) # ???

def some_other_method a
# ... doing something with a
end

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:

some_array.each(&method(:puts))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download