Currently, I am new to programming learning for 2 months. This time, I would like to describe what happens when you put each statement in each statement in ruby.
Specifically, it is as follows. ① What kind of movement is it when you put the each sentence in the each sentence? ② How to check the movement
In addition, each statement in each statement assumes the following.
sample1.rb
#It is described briefly.
array.each do |i|
array.each do |num|
end
end
I hope it will be a plus for those who are just starting the same learning as me!
This time, I added a little description to the above code for the sake of clarity. Use the code below.
sample2.rb
array = [1,2,3]
array.each do |i|
puts i
array.each do |num|
puts num
end
end
So, let me tell you from the conclusion what kind of movement it is doing When one element is taken out, all the elements are displayed.
sample3.rb
1 #When one element is taken out
1 #Show all elements
2 #Show all elements
3 #Show all elements
2
1
2
3
3
1
2
3
I will describe it a little more concretely.
The movement of each method is the following image. ① Take out one element from the array. (2) Use the extracted element as a block variable. ③ Perform the described processing while using block variables. (4) Repeat the process for the number of elements in the array.
This time, after extracting one element from the array, the each statement comes again.
So, according to the previous image, (1) Extract the element "1" from array. ② Let 1 be the block variable "i" (3) Display i and implement each method for the array of array. Extract the element "1" from the array. Let 1 be the block variable "num" Display num Repeat the process up to 1, 2 and 3. ④ Repeat the process up to 1, 2 and 3.
It will be. The point is that one is taken out, all are taken out, one is taken out, and all are taken out.
From the conclusion, I confirmed it while running it on the terminal. Somehow, there is a way to check what kind of result you get by running it on the terminal For now, I think it's reliable and fast.
Recently, I mainly do the following flow. ① Make a hypothesis ② Think about how you can verify it, and actually write it with vs code ③ Try to implement with terminal ④ If the result is different from what you expected, make a hypothesis again.
I also confirmed how the each statement behaves in each statement by the above method. The point is ②. Anyway, I think the point here is to write it simply without any unnecessary things.
Originally, the following problems came up during learning. "Check if the elements in the array are duplicated."
At this time, I put each statement in each statement and compare the elements one by one. I didn't really understand this process, I was wondering how to understand it. At that time, why not just write it in a simple way and implement it? I came up with.
For now, this method makes it easier to get an image of the process flow.
Recommended Posts