简体   繁体   English

Ruby块隐式变量

[英]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: 我想知道Ruby是否具有像Scala中那样的隐式块参数或通配符,可以绑定并用于进一步执行,如下所示:

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: 有一些类似于proc的符号,它从集合中调用每个元素的一些方法,如: array_of_strings.each &:downcase ,但我不想在循环中执行对象的方法,而是以此对象作为参数执行一些函数:

my_collection.each { my_method(_) }

instead of: 代替:

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

Is there any way to do that in Ruby? 在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是在Object类上定义的方法,返回Method类的实例。 Method instance, similarly to symbols, defines to_proc method, so it can be used with unary & operator. Method实例与符号类似,定义了to_proc方法,因此它可以与一元&运算符一起使用。 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. 此运算符获取定义to_proc方法的proc或任何对象,并将其转换为块,然后将其传递给方法。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM