Ruby Block Implicit Variables

I wonder if Ruby has something like implicit block parameters or wildcards, like in Scala, which can be connected and used in further execution as follows:

my_collection.each { puts _ }

or

my_collection.each { puts }

There is something like a proc symbol, which calls a method for each element in the collection, for example: array_of_strings.each &:downcasebut I do not want to execute the object method in the loop, but I perform some function with this object as a parameter:

my_collection.each { my_method(_) }

instead:

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

Is there any way to do this in Ruby?

+4
source share
1 answer

You should be able to do this with

my_collection.each &method(:my_method)

method - , Object, method. method , , to_proc, &. proc , to_proc , . , , :

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

:

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

:

[1,2,3,4].each.with_index do |a,b|
  puts "#{b}: #{a}"
end
+7

Source: https://habr.com/ru/post/1543207/


All Articles