What can procs and lambdas do that functions can't in ruby

Posted by SecurityGate on Programmers See other posts from Programmers or by SecurityGate
Published on 2012-10-03T16:08:33Z Indexed on 2012/10/03 21:54 UTC
Read the original article Hit count: 268

Filed under:
|
|

I've been working in Ruby for the last couple weeks, and I've come to the subject of procs, lambdas and blocks. After reading a fair share of examples from a variety of sources, I don't how they're much different from small, specialized functions. It's entirely possible that the examples I've read aren't showing the power behind procs and lambdas.

def zero_function(x)
    x = x.to_s
   if x.length == 1
    return x = "0" + x
   else
    return x
   end
end

zero_lambda = lambda {|x|
  x = x.to_s
   if x.length == 1
    return x = "0" + x
   else
    return x
   end
}

zero_proc = Proc.new {|x|
  x = x.to_s
   if x.length == 1
    puts x = "0" + x
   else
    puts x
   end
}


puts zero_function(4)
puts zero_lambda.call(3)
zero_proc.call(2)

This function, proc, and lambda do the exact same thing, just slightly different. Is there any reason to choose one over another?

© Programmers or respective owner

Related posts about ruby

Related posts about functions