简体   繁体   中英

Ruby block implicit variables

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?

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

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