Where and when to use Lambda?

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

    Blocks are more-or-less the same thing

    Well, in Ruby, one doesn't usually use lambda or proc, because blocks are about the same thing and much more convenient.

    The uses are infinite, but we can list some typical cases. One normally thinks of functions as lower-level blocks performing a piece of the processing, perhaps written generally and made into a library.

    But quite often one wants to automate the wrapper and provide a custom library. Imagine a function that makes an HTTP or HTTPS connection, or a straight TCP one, feeds the I/O to its client, and then closes the connection. Or perhaps just does the same thing with a plain old file.

    So in Ruby we would put the function in a library and have it take a block for the user .. the client .. the "caller" to write his application logic.

    In another language this would have to be done with a class that implements an interface, or a function pointer. Ruby has blocks, but they are all examples of a lambda-style design pattern.

提交回复
热议问题