Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't get the idea behind Ruby Proc... why not just use normal Method?

I guess the title says it. I'm reading a book and I can see how they work but why would I create them instead of normal methods with normal parameters?

I searched Google and SO I just got confused more.

Please clarify. Thanks.

like image 534
emurad Avatar asked Dec 17 '22 13:12

emurad


1 Answers

A proc is different because you can store it in a variable. Therefore you can pass it as a paramater to a function, return it from a function, manipulate it, etc.

Procs, lambdas and blocks are one of the main things that make Ruby awesome.They are at the heart of Ruby's iterators for example. When you do something like:

collection.each do |item|
 //process item
end

you are basically passing a block (a Proc object) to the each function.

Let's say you a bunch of arrays, that you want to process in the same way. To save you from writing the each code every single time you can do something like:

handler = Proc.new{|item| do_something_with(item)}
array1.each &handler
array2.each &handler
....
arrayn.each &handler

When you want to pass a Proc to a function as a block, you have to preceed it with an &. The same goes for when you define a function that accepts a block parameter.

Another useful way to use Proc, is in functions.

Say you have a function that instantiates an object, does some minor changes, and returns it. To make it more flexible, you can make it accept a block like so:

def new_item(param1, param2, &block)
  my_item = Item.new
  my_item.attribute1 = param1
  my_item.attribute2 = param2
  yield my_item if block_given?\
  return my_item
end

Yield is where the magic happens. When that line is evaluated, the function will execute the block that you give it with my_item as a parameter. So you can do stuff like:

my_new_item = new_item(p1, p2) do |item|
  item.attribute3 = some_value
end

Now, my_new_item will have its attribute3 set as well as any other modification than you do in the block.

You don't use Procs and lambdas to replace functions, you use them to augment functions. You can have a function that returns a Proc that was built based on whatever parameters you give it. There are a lot of ways to be creative with Procs.

like image 111
adivasile Avatar answered May 08 '23 09:05

adivasile