简体   繁体   中英

Idiomatic way to convert class method to proc in ruby

Suppose I want to describe Kernel.puts using a Proc. 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? 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 :

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

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 . So I will give my answer.

You cannot do that using 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. 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) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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