The use of simple methods
There is a list of strings that need to be converted to uppercase for each of these strings, and we can do it in a simple notation.
Copy Code code as follows:
Name_list = ["Chareice", "Angel"]
Name_list.map (&:upcase)
# => ["Chareice", "ANGEL"]
This is equivalent to
Copy Code code as follows:
Name_list.map do {|name| name.upcase}
Simple writing is a very obvious efficiency improvement, but this seemingly magic parameters, behind the principle is what?
& Symbols
If you remove the & symbol above the method call, it is obvious to see that the upcase is passed to the method as the parameter of the method.
In fact, the,& symbol represents a block transition to proc (Block-to-proc conversion). Let's look at an example below.
Copy Code code as follows:
def capture_block (&block)
Block.call
End
Capture_block {puts "I have a little donkey, I never ride it." " }
# => I have a little donkey, I never ride it.
We run the Capture_block function, pass a code block to it, and the code block passes through the conversion of the & symbol into a proc object passed into the function, in the example above is the blocks variable. If we output the block class, the output will be proc.
You can also pass a proc object to Capture_block instead of a code block.
Copy Code code as follows:
p = proc.new {puts "and give a little donkey"}
Capture_block (&P)
# and => to a little donkey
It seems that the & symbol is superfluous and can be completely removed and the results of the operation are the same.
What did the & sign do?
Take the Capture_block (&p) call as an example.
1. To_proc method of triggering p.
2. Tell the Ruby interpreter to use the result returned by the To_proc method as the block of this function call.
If you use both A & symbol and an incoming block to a function, Ruby will complain.
Copy Code code as follows:
Capture_block (&p) {puts to "pass to a block"}
#=>syntaxerror: (IRB): 30:both block Arg and actual block given
So a proc object is passed to the & symbol, which invokes the To_proc method of the Proc object, returns itself, and passes it to the method as the block of the method call.
What is &:upcase?
Knowing the role of the & symbol, we can see that &:upcase is called First: the To_proc method of the UpCase object.
: UpCase's To_proc method is implemented as follows:
Copy Code code as follows:
Class Symbol
def To_proc
proc.new {|obj| obj.send (self)}
End
End
The result is clear, Symbol#to_proc will return a proc object with parameters, and the Proc object is to send a method that invokes the name of the symbol for the object that uses the Proc object.