Proc Objects
Proc are objects that are converted by blocks. There are four ways to create a proc, respectively:
Sample code
# Law one
inc = Proc.new {| x | x + 1}
Inc.call (2) #=> 3
# method two
inc = Lambda {| x | x + 1}
Inc.call (2) # => 3
# method three
inc =-> (x) {x + 1}
Inc.call (2) #=> 3
# method four
inc = proc {|x| x + 1}
Inc.call (2) #=> 3
In addition to the above four, there is a way through the & operator, the code block and proc object conversion. If you need to pass a code block as a parameter to a method, you need to add a & symbol to the parameter, and its position must be at the last
The meaning of & symbol is: This is a proc object, I want to use it as a block of code. Remove the & symbol and get a proc object again.
Sample code
def my_method (&the_proc)
the_proc
end
p = my_method {|name| "Hello, #{name}!"}
P.class #=> Proc
p.call ("Bill") #=> "Hello,bill"
def my_method (greeting)
"#{" Greeting}, #{yield}! "
End
My_proc = proc {"Bill"}
My_method ("Hello", &my_proc)
Some places to be aware of
When using block, I will ignore the existence of proc, and I will position proc as a worker behind the scenes. I often write code similar to the following
def f (...)
...
Yield ...
End
def f (..., &p)
...
P.call ...
End
def f (..., &p)
instance_eval &p
...
End
def f (..., &p)
...
Defime_method m, &p ...
End
Some beginners will write code similar to the one in which the following execution will report an error.
Def f (..., &p)
instance_eval P end
def f (..., p)
instance_eval p.call
End
There is also this written,
Def f (..., &p) instance_eval do
P.call end
Or
def f (...)
Instance_eval do
yield
end
I even wrote code similar to the following
def f (...)
Instance_eval yield End
We often have to hang block, but the proc object when the argument to the method, or do not understand &p is block can be directly to the use of methods, I have made such a mistake is because the block and proc the correct distinction between, & P is block, P is proc, do not explicitly create proc without the last resort, I will read a few words when I am confused about the relationship between Block and Proc.