Nathan Nathan - 6 months ago 47
Ruby Question

Why use procs instead of methods?

I'm new to programming, and ruby is my first real run at it. I get blocks, but procs seem like a light method/function concept -- why use them? Why not just use a method?

Thanks for your help.


Proc is a callable piece of code. You can store it in a variable, pass as an argument and otherwise treat it as a first-class value.

Why not just use a method?

Depends on what you mean by "method" here.

class Foo
  def bar
    puts "hello"

f =

In this code snippet usage of method bar is pretty limited. You can call it, and that's it. However, if you wanted to store a reference to it (to pass somewhere else and there call it), you can do this:

f =
bar_method = f.method(:bar)

Here bar_method is very similar to lambda (which is similar to Proc). bar_method is a first-class citizen, is not.

For more information, read the article mentioned by @minitech.