A method that can be used for numeric objects. Repeat the process enclosed in do ~ end
for the number of numbers.
I dare to start with the conclusion.
・ ~~ Block variable ~~ Block parameter is valid only in the block (scope) -Those defined outside can also be used inside the block (note that they can be rewritten) </ font>
Put this in the corner of your head and read on.
The scope is the range in which the defined variables can be used.
do~end
Or{ }
(Curly braces)The inside is called a block. In addition, in the block|Variable name|
||Variables in (pipeline)~~Block variable~~It is called a block parameter.
STEP1
To make sure you understand it, start here.
num = 1
puts num
#=>1
Such a program appears at the very beginning of variables. To explain it carefully, the numerical value 1 is assigned to the variable num, and it is called by puts. I'm not aware of it, but since it is the scope of the variable num, it can be called with puts.
STEP2
num = 1
3.times do
puts num
end
#=>1
# 1
# 1
This resulted in puts num
being repeated 3 times and a" 1 "3 times. Of note is the scope of the variable num. Variables defined outside do ~ end
can be used.
STEP3
3.times do
num = 1
end
puts num
#=>NameError
The code is similar to STEP2, but I get an error. ↓
NameError (undefined local variable or method num for main:Object)
The simple translation is " num
in puts num
is not defined".
Yes, anything defined inside do ~ end
cannot be called outside do ~ end
.
Actually, a stumbling point! !!
STEP4
num = 1
3.times do|i|
num = num + i
end
puts num
#=>4
Points to read ① ~~ Block variable ~~ Block parameters start from 0 and increase by 1. In the above example, it is considered that "0" is substituted in the first week, "1" is substituted in the second week, and "2" is substituted in the third week.
(2) The external variables have been rewritten.
If you write it carefully ↓ Week 1 num + 0 => num is defined as 1, so "1 + 0" is assigned to num. 2nd week num + 1 => From the above, num is 1 and since it is the 2nd week, i changes to 1 and "1 + 1" is assigned to num. 3rd week num + 2 => From the above, num is 2, and since it is the 3rd week, i changes to 2 and "2 + 2" is assigned to num.
-[x] ~~ Block variable ~~ As the name suggests, block parameters are valid only within blocks. -[x] Variables defined outside the block can be rewritten by processing inside the block.
Regarding iterative processing, it is a content that you can learn programming at an early stage, and even if you think you understand it, you may not remember the details, so take this opportunity to review it.
Recommended Posts