Wednesday, March 21, 2012

QA : 1 : Proc

Well, the first question from Apoorv Parijat..
Thanks Apoorv for starting this tag as this is the very first question for Question and Answers

Question :
In what scenarios using Proc.new proves helpful? (and better than lambda)

2 comments:

  1. Proc.new is more useful when we consider the arguments. As Proc.new first check the number of parameters which are passed.
    So if pass extra parameter lambda will throw an error indicating that wrong number of arguments.
    But in Proc.new the extra parameter will be discarded.

    You can also use proc.new when you want to directly skip from method which it contains.
    So if you write "return if something" in proc.new you can skip the method it self. (Ofcourse if thats the requirement)

    For example
    def method(params1, params2)
    c = Proc.new {|x, y| return "Not Valid" if x==y}
    c.call(params1, 0)
    puts "Ok, We just skipped the proc new"
    end

    and now try
    method(4, 5) #"Ok, We just skipped the proc new"
    method(0, 9) #"Not Valid"

    Check the screenshot for this example.

    And if the similar thing you do it in lambda you will just get skipped from the lambda and not the from the method.

    ReplyDelete
  2. Ah. this is helpful.
    Thanks for the quick response.

    I think the difference of point of return is a tricky one and
    should always be kept in mind. Also, I can hardly think of
    any scenario where I'll be using Proc.new.

    It's sad Ruby's method don't share the default scope.

    ReplyDelete