Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to convert class method to proc in ruby

Tags:

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.

like image 553
George Simms Avatar asked Jan 02 '16 23:01

George Simms


People also ask

What does &: mean in Ruby?

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.

What is To_proc Ruby?

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.

What is proc and lambda in Ruby?

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.


3 Answers

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

like image 165
Wand Maker Avatar answered Oct 13 '22 07:10

Wand Maker


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
like image 22
yez Avatar answered Oct 13 '22 05:10

yez


I think you just want Object#method:

meth = Kernel.method(:puts)
meth["hello"]
# => hello
like image 34
Jordan Running Avatar answered Oct 13 '22 07:10

Jordan Running