Where and when to use Lambda?

后端 未结 7 2016
执笔经年
执笔经年 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:27

    1) It is just a convenience. You don't need to name certain blocks

    special_sort(array, :compare_proc => lambda { |left, right| left.special_param <=> right.special_param }
    

    (imagine if you had to name all these blocks)

    2) #lambda is usually used to create clojures:

    def generate_multiple_proc(cofactor)
      lambda { |element| element * cofactor }
    end
    
    [1, 2, 3, 4].map(&generate_multiple_proc(2)) # => [2, 3, 5, 8]
    
    [1, 2, 3, 4].map(&generate_multiple_proc(3)) # => [3, 6, 9, 12]
    

提交回复
热议问题