5

I wonder if Ruby has something like implicit block parameters or wildcards as in Scala that can be bound and used in further execution like this:

my_collection.each { puts _ }

or

my_collection.each { puts }

There's something like symbol to proc that invokes some method on each element from collection like: array_of_strings.each &:downcase, but I don't want to execute object's method in a loop, but execute some function with this object as a parameter:

my_collection.each { my_method(_) }

instead of:

my_collection.each { |f| my_method(f) }

Is there any way to do that in Ruby?

1 Answer 1

7

You should be able to do it with:

my_collection.each &method(:my_method)

method is a method defined on Object class returning an instance of Method class. Method instance, similarly to symbols, defines to_proc method, so it can be used with unary & operator. This operator takes a proc or any object defining to_proc method and turns it into a block which is then passed to a method. So if you have a method defined like:

def my_method(a,b)
  puts "#{b}: #{a}"
end

You can write:

[1,2,3,4].each.with_index &:method(:my_method)

Which will translate to:

[1,2,3,4].each.with_index do |a,b|
  puts "#{b}: #{a}"
end
Sign up to request clarification or add additional context in comments.

1 Comment

To avoid & interpreted as argument prefix warning add parenthesis around &method like my_collection.each(&method(:my_method))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.