简体   繁体   English

如何在Ruby中将方法转换为proc以用于&method

[英]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 a Method object (or raising NameError ). 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.

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