[英]How to convert method to proc for &method usage in Ruby
For learning purposes, I'm exploring if I can convert these three method calls: 为了便于学习,我探索,如果我可以转换这三个方法调用:
Foo::Bar.logger.debug(a)
Foo::Bar.logger.debug(b)
Foo::Bar.logger.debug(c)
into a single-line statement using the shorthand proc &method
approach: 使用简写的proc &method
方法转换为单行语句:
[a, b, c].each(&method(:'Foo::Bar.logger.debug'))
.debug
does not respond to .to_proc
so naturally: .debug
不会自然地响应.to_proc
:
NameError: undefined method `Foo::Bar.logger.debug' for class `#<Class:Foo>'
This does work; 这确实有效; however, but isn't as succinct as the former: 但是,它不像前者那么简洁:
logger = Proc.new { |x| Foo::Bar.logger.debug(x) }
[a, b, c].each(&logger)
Is it possible for the former approach to work? 是否有可能为前者的工作方式?
You're using the method
method incorrectly. 您使用的method
方法不正确。 From the fine manual : 从精美的手册中 :
method(sym) → method 方法(符号)→方法
Looks up the named method as a receiver in obj , returning aMethod
object (or raisingNameError
). 在obj中查找命名方法作为接收器,返回一个Method
对象(或引发NameError
)。
You'd usually say 你通常会说
m = some_obj.method(:some_method_name)
and then work with m
. 然后与m
。 Saying: 说:
method(:Foo::Bar.logger.debug)
should be giving you a TypeError
because because :Foo
is a symbol, not a class or module and trying to apply ::
to a symbol makes no sense. 应该给你一个TypeError
因为因为:Foo
是一个符号,而不是一个类或模块,并且试图将::
应用于符号没有意义。 I suspect that you're actually saying: 我怀疑您实际上是在说:
method(':Foo::Bar.logger.debug')
as that will produce the error you're seeing. 因为那样会产生您所看到的错误。 Assuming that that's the case, then you're actually trying to get a reference to the method named ':Foo::Bar.logger.debug'
in the object self
. 假设是这种情况,那么您实际上是在尝试获取对象self
名为':Foo::Bar.logger.debug'
的方法的引用。
If you want a reference to the debug
method in Foo::Bar.logger
then you'd say: 如果要在Foo::Bar.logger
引用debug
方法,则可以说:
Foo::Bar.logger.method(:debug)
Combining that your to_proc
call (via &
): 结合您的to_proc
调用(通过&
):
[a, b, c].each(&Foo::Bar.logger.method(:debug))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.