Block, lambda, and proc are important in ruby.
- A block is an anonymous function. It is called using a field in the called method. Block is mainly used for iteration.
RubyCode:
Arr = [1, 2, 4, 5]
Arr. Each {| item | puts item}
Proc is also a code block, which is equivalent to a process.
Ruby code:
A_proc = Proc. New {| A, * B | B. Collect {| I * }}
A_proc.call (9, 1, 2, 3) # => [9, 18, 27]
When Proc. New creates a proc object, it does not contain a block, but it only includes a block on the method for defining Proc. This block will become Proc.
Ruby code:
Def proc_from
Proc. New
End
Proc = proc_from {"hello "}
Proc. Call # => "hello"
The proc object is a code block bound to a local variable. After binding, the code can be called in different contexts and can access local variables.
Ruby code
Def gen_times (factor)
Return Proc. New {| n | N * factor}
End
Times3 = gen_times (3)
Times5 = gen_times (5)
Times3.call (12) # => 36
Times5.call (5) # => 25
Times3.call (times5.call (4) # => 60
Lambda is also an anonymous function.
Ruby code
A_lambda = Lambda {| A | puts}
A_lambda.call ("samsam ")
Lambda returns a proc object.
Ruby code
A_lambda.class # => proc
Lambda and proc are the same, except that the return of Proc will jump out of the called method, Lambda will not, It just returns itself.
Ruby code
Def foo
F = Proc. New {return "return From Foo from inside proc "}
F. Call # control leaves foo here
Return "return from foo"
End
Def bar
F = Lambda {return "return from lambda "}
Puts F. Call # control does not leave bar here prints "return from lambda"
Return "return from Bar"
End
Puts Foo # prints "return From Foo from inside proc"
Puts bar # prints "return from Bar"