InQusitive InQusitive - 20 days ago 8
Ruby Question

How does this create a proc object?

def makeProc(&obj)
obj
end

puts makeProc{|x,y| x+y}.class


How does obj become a Proc type when a block is passed to it as reference? Is there any reason or it is like some kind of ruby magic?

Answer

When you call makeProc with the block { |x,y| x + y }, Ruby instantiates a new Proc object using Proc.new:

Proc.new { |x,y| x + y }

and it is assigned to obj. It knows to do this conversion when it sees the & character in the method definition.