Where and when to use Lambda?

后端 未结 7 2119
执笔经年
执笔经年 2021-01-31 16:47

I am trying to understand why do we really need lambda or proc in ruby (or any other language for that matter)?

#method
def add a,b
  c = a+b
end

#using proc
de         


        
7条回答
  •  渐次进展
    2021-01-31 17:33

    I found this helpful in understanding the differences:

    http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/

    But in general the point is sometimes your writing a method but you don't know what you're going to want to do at a certain point in that method, so you let the caller decide.

    E.g.:

    def iterate_over_two_arrays(arr1, arr2, the_proc)
      arr1.each do |x|
        arr2.each do |y|
          # ok I'm iterating over two arrays, but I could do lots of useful things now
          #  so I'll leave it up to the caller to decide by passing in a proc
          the_proc.call(x,y)
        end
      end
    end
    

    Then instead of writing a iterate_over_two_arrays_and_print_sum method and a iterate_over_two_arrays_and_print_product method you just call:

    iterate_over_two_arrays([1,2,3], [4,5,6], Proc.new {|x,y| puts x + y }
    

    or

    iterate_over_two_arrays([1,2,3], [4,5,6], Proc.new {|x,y| puts x * y }
    

    so it's more flexible.

提交回复
热议问题