Last Updated: February 25, 2016
·
592
· ready4god2513

Secrets of Proc.new

I was looking through the Ruby docs (as all good devs do, right?) and I was thinking about how a few of the methods could be reimplemented in Ruby itself. Obviously this is just a for fun exercise. But I came across Kernel#loop and got stuck. How can that be implemented? Passing a block is easy. But how about forwarding it? Not so easy.

If the method signature accepts no arguments, how could it be implemented? You can't pass along a call to yield, can't pass in &block. The secret is Proc.new Interestingly enough if the message is sent without an attached block, the block in which it is called is converted and sent to the proc.

def my_loop
  yield if block_given?
  my_loop(&Proc.new)
end

n = 0

my_loop do
  break if n >= 100
  n += 1
  puts "testing #{n}"
end

For more information, check out this great article- http://mudge.name/2011/01/26/passing-blocks-in-ruby-without-block.html

1 Response
Add your response

Ok, I was wrong about passing yield. You can pass it in a block my_loop { yield }, just not as an argument. But still standing is how cool Proc.new actually can be.

over 1 year ago ·