Tutorial on block code blocks in Ruby and tutorial on rubyblock code
1. What is a code block?
In Ruby, the code between {} Or do... end is a code block. A code block can only appear behind a method. It is called by the yield keyword on the same line of the last parameter of the method. For example:
[1,2,3,4,5].each { |i| puts i }[1,2,3,4,5].each do |i| puts iend
Block variables: You can call a block with the yield keyword to pass parameters. The parameter names provided between the vertical bars (|) in the block are used to receive parameters from yield.
The variables between the vertical bars (| I | in the preceding example) are called block variables, which act the same as parameters of a normal method.
2. compile code blocks
Blocks is the most common, simple, controversial, and Ruby-style method. The statement is as follows:
array = [1, 2, 3, 4]array.collect! do |n| n ** 2endputs array.inspect# => [1, 4, 9, 16]
Do... End forms a block. Then pass this block through collect! To an array. You can use n in the block to iterate each element in the array.
Collect! Is the method in the Ruby library. Next we will write our own similar method iterate!
class Array def iterate! self.each_with_index do |n, i| self[i] = yield(n) end endendarray = [1, 2, 3, 4]array.iterate! do |n| n ** 2endputs array.inspect# => [1, 4, 9, 16]
First, open Array and add it to iterate! Method. The method name is! It indicates a dangerous method at the end. Now we may be using collect! Use iterate!
Unlike the attribute, you do not need to specify the block name in the method, but use yield to call it. Yield executes the code in the block. At the same time, note how we pass n (number currently processed by each_with_index) to yield. The parameter passed to yield corresponds to the parameter (| part of the block ). Now n can be called by block and n ** 2 will be returned in yield call.
The entire call is as follows:
1. An array composed of integers calls iterate!
2. When yield is called, set n (1 for the first time, 2 for the second time ,...) Pass to block
3. block n ** 2. Because it is the last row, it is automatically returned as a result.
4. yield gets the block result and overwrites the value to the array.
5. Each object in the Data performs the same operation.
3. The priorities of {} and do... end are different.
When passing a block, use the block passed by {} to use do... The priority of end is high;
To avoid ambiguity, it is best to use () to enclose parameters. For example:
1.upto 3 do |x|puts xend
Yes, but 1. upto 3 {| x | puts x} is not compiled. It should be written as 1. upto (3) {| x | puts x}
Cause:
1. upto 3 do... In the end, the block is passed to the upto method, and 3 is passed to the upto method as a parameter.
1. the upto 3 {| x | puts x} clause uses 3 as the function name and passes the block to this function. The returned value is used as the parameter of the upto method. Therefore, it cannot be compiled, add ().