Wednesday, November 6, 2013

Ruby: procs and lambdas

Procs:
Sometimes you need to pass block to your method. The problem is that you cant save block to variable, because it is not an object. If you need to pass one block to many methods, there's no need to the same block over and over again, because you can make Proc. Proc saves your block to variable, and gives you an opportunity to manipulate with it like with object.

proc_name = Proc.new { your block here }

func1(&proc_name)
func2 &proc_name
You must pass proc to method with & symbol.

Also you can convert symbols to procs using magic & symbol:
(function .map and .collect runs through all the elements in array)
number = [0,1,2]
number.map(&:to_s) // This will convert 0,1,2 to strings
Lambda:Lambdas are almost the same as procs, with the exception of syntax and few behavioral features.

Proc.new { puts "Hello" }
same as
lambda { puts "Hello!" }
Differencies between lambdas and procs:
1. Lambda checks the number of arguments passed to it, while a proc does not. Lambda will throw an error, proc will assign nil to all unassigned arguments.
2.When a lambda returns, it passes control back to the calling method; when a proc returns, it returns immediately, whithout passing control back.

// Outputs "Hello world!"
def A
  h = Proc.new { return "Hello world!" }
  h.call
  return "Hello galaxy!"
end

// Outputs "Hello galaxy!"
def B
  h = lambda { return "Hello world!" }
  h.call
  return "Hello galaxy!"
end

Infromation from: www.codeacademy.com

No comments:

Post a Comment