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"
end
end
f = Foo.new
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 = Foo.new
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, f.bar
is not.
For more information, read the article mentioned by @minitech.