Since I learned about blocks to deepen my understanding of Ruby, I will output it.
--do ~ end
is called a block in Ruby.
|i|
I is~~Block argument~~Called a block parameter.For example, such a problem because it is easier to understand if there is an example. (There are other ways to solve it, but this time the times sentence
)
** A block is an argument of the times
method. It is repeated by writing in do ~ end
so that iterative processing is performed according to the contents of the block. ** **
[Problem] Add the numbers from 1 to 10 in order, and output the result of adding all at the end to the terminal.
sum = 0
10.times do |i|
sum += i + 1
end
puts sum
#Terminal output result
# 55
In the above problem, I used do ~ end
. There are other ways to write blocks.
For example, it looks like this.
sum = 0
10.times { |i| sum += i + 1 }
puts sum
#Terminal output result
# 55
By enclosing do ~ end
with{}
, Ruby recognizes it as a block.
Each person has their own way of writing, but keep in mind that there is such a way of writing.
It seems that {}
is used when it fits in one line, and do ~ end
is used for long code including line breaks.
yield
The normal
method is called and puts is output.
##Normal calling
def normal
puts 'nomal method call'
end
normal
#Terminal output result
#nomal method call
The block (do ~ end) passed to the nomal method is called.
##Call the block passed when calling the nomal method with yield
def normal
puts 'nomal method call'
yield
end
normal do
puts 'Call with yield'
end
#Terminal output result
#nomal method call
#Call with yield
By putting an argument in yield
when calling the block, any thing (argument value) is passed to the block.
def normal
puts 'nomal method call'
yield('Give an argument')
end
#The argument is passed to the block by giving an argument to yield
normal do |text|
puts text
end
#Terminal output result
#nomal method call
#Give an argument
point --nomal (& block argument) --Block argument .call (argument you want to pass to the block)
def normal(&block) #In the argument block&Put on
puts "nomal method call"
block.call("Give an argument") #Block with call method(block)Run
end
normal do |text|
puts text
end
--There are "do ~ end" and "{}" in the block. ――You can write clearly by using "{}". --Use "{}" if it fits on one line, and "do ~ end" if you need a line break. You can execute the block passed to the method by using --yield. --~~ If you want to execute the block explicitly, add & before the argument. ~~ --~~ The block received as an argument can be called with the "call method". ~~ --In order to receive the block as a Proc object, add & before the argument. --Use the call method to receive and execute the block.
-Ruby 2.7.0 Reference Manual -[Block? yield? ] A solid understanding of Ruby's Proc objects
Recommended Posts