Explain the code block object Proc in Ruby, and explain the ruby object proc.
Proc object
Proc is a block conversion object. There are four methods to create a Proc:
Sample Code
# Method 1 inc = Proc. new {| x + 1} inc. call (2) #=> 3 # method 2 inc = lambda {| x + 1} inc. call (2) #=> 3 # method 3 inc =-> (x) {x + 1} inc. call (2) #=> 3 # Method 4 inc = proc {| x + 1} inc. call (2) # => 3
In addition to the above four types, there is also a way to convert code blocks and Proc objects through the & operator. If you want to pass a code block as a parameter to the method, you need to add the & symbol for this parameter, and its position must be at the end of the Parameter
& The meaning of the symbol is: this is a Proc object. I want to use it as a code block. Remove the & symbol to get a Proc object again.
Sample Code
def my_method(&the_proc) the_procendp = my_method {|name| “Hello, #{name} !”}p.class #=> Procp.call(“Bill”) #=> “Hello,Bill”def my_method(greeting) “#{greeting}, #{yield}!”endmy_proc = proc { “Bill” }my_method(“Hello”, &my_proc)
Notes
When using block, I will ignore the existence of proc, And I will position proc as a working person 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 new users will write code similar to the following, which will report an error,
def f(..., &p) instance_eval p end def f(..., p) instance_eval p.call end
This is also the case,
def f(..., &p) instance_eval do p.call end end
Or
def f(...) instance_eval do yield end end
I have even written code similar to the following,
def f(...) instance_eval yield end
We often pass the proc object as a parameter to the method when the block is mounted, or we do not understand that & p is the block which can be directly handed over to the method for use, I have also made this mistake because I didn't distinguish block from proc correctly. & p is block, p is proc, do not explicitly create a proc unless you have to. Whenever I am confused about the relationship between block and proc, I will read a few words.