Search code examples
rubylambdablock

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?


Solution

  • 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