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.
In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.
to_proc returns a Proc object which responds to the given method by symbol. So in the third case, the array [1,2,3] calls its collect method and. succ is method defined by class Array.
Blocks are syntactic structures in Ruby; they are not objects, and cannot be manipulated as objects. It is possible, however, to create an object that represents a block. Depending on how the object is created, it is called a proc or a lambda.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With