简体   繁体   English

在ruby中将类方法转换为proc的惯用方法

[英]Idiomatic way to convert class method to proc in ruby

Suppose I want to describe Kernel.puts using a Proc.假设我想使用 Proc 描述Kernel.puts How would I do this ?我该怎么做?

I can think of a number of possibilities;我能想到很多可能性;

Proc.new do |*args| Kernel.puts *args end
:puts.to_proc.curry[Kernel] # doesn't work, returns `nil` as puts is varargs

But both are quite verbose.但两者都相当冗长。

Would method be what you're looking for? method会是你要找的吗? It can let you save a method to a variable.它可以让您将方法保存到变量中。

2.1.0 :003 > m = Kernel.method(:puts)
 => #<Method: Kernel.puts>
2.1.0 :004 > m.call('hi')
hi

I think you just want Object#method :我想你只想要Object#method

meth = Kernel.method(:puts)
meth["hello"]
# => hello

You can pass the receiver object as first parameter, and actual argument as subsequent parameters.您可以将接收者对象作为第一个参数传递,将实际参数作为后续参数传递。

:puts.to_proc.call(Kernel, "Hi")
#=> Hi

I found this article - RUBY: SYMBOL#TO_PROC IS A LAMBADASS - to be quite informative on behavior of lambdas returned by Symbol#to_proc我发现这篇文章 - RUBY: SYMBOL#TO_PROC IS A LAMBADASS - 对Symbol#to_proc返回的 lambdas 的行为提供了非常丰富的信息

I have no idea why the answer got accepted got accepted, as it is not what was asked.我不知道为什么答案被接受了,因为这不是被问到的。 That answer takes the string as the argument, whereas the OP wanted to pass Kernel .该答案将字符串作为参数,而 OP 希望通过Kernel So I will give my answer.所以我会给出我的答案。

You cannot do that using Symbol to Proc .您不能使用Symbol to Proc来做到这一点。 I think you are confusing the receiver and the arguments.我认为你混淆了接收者和论点。 Symbol to Proc creates a proc that takes the receiver as the variable, not its arguments. Symbol to Proc创建了一个 proc,它将接收者作为变量,而不是它的参数。 And, currying modifies the arity of the arguments;并且,柯里化修改了参数的数量; it has nothing to do with the receiver.它与接收器无关。

proc = proc {  |*args| Kernel.puts(args) }

或使用 lambda

proc = ->(*args) {Kernel.puts(args) }

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

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