This is a personal memo.
By using each method, you can extract elements such as arrays and objects one by one and perform processing using their values.
--for statement: Valid outside -Each method: Valid only during. Not valid outside.
The each method is better if you want to write the process neatly. The disadvantage is that the variable is separated from the outside, so the amount of processing is slightly larger. (Almost no need to worry)
・object.each {|variable|processing}
┗ Object is iterable
┗Variable contains each extracted value
┗ {}
is called ** block **
block{}
Isdo |variable|Processing end
Same as.
Since it is non-destructive, the original object remains the same. Also, even if it is assigned to another variable, it will be the same as the original object.
python
range1 = 1..3
range2 = (1..3).each{|x| y = x*2; p y }
#2
#4
#6
p range1 #1..3
p range2 #1..3
python
(1..3).each{|x| p x}
##output
1
2
3
The range object contains the ending value if there are two dots. Not included in 3 cases.
python
1..3.each{|x| p x}
NoMethodError (undefined method `each' for 3:Integer)
python
range1 = 1..3
range1.each{|x| p x}
##output
1
2
3
python
for x in 1..3
p x
end
##output
1
2
3
python
arr = [1, 2, 3]
arr.each{|x| p x}
##output
1
2
3
Of course, arr remains the same after processing.
Number of variables | Contents | Example of acquisition element |
---|---|---|
1 | Key and value | [:a, 1] |
2 | 1st argument: key, 2nd argument: value, | :a, 1 |
When there is one argument
obj = {:a=>1, :b=>2, :c=>3}
obj.each{|x| p x}
##output
[:a, 1]
[:b, 2]
[:c, 3]
** ▼ key only output **
python
obj = {:a=>1, :b=>2, :c=>3}
obj.each{|x, y| p x}
#output
:a
:b
:c
** ▼ Output only value **
python
obj = {:a=>1, :b=>2, :c=>3}
obj.each{|x, y| p y}
#output
1
2
3
Same as specifying one variable in each block. Extract keys and values as an array of sets.
When there is one argument
obj = {:a=>1, :b=>2, :c=>3}
obj.each_pair{|x| p x}
##output
[:a, 1]
[:b, 2]
[:c, 3]
Method to retrieve only key
python
obj = {:a=>1, :b=>2, :c=>3}
obj.each_key{|x| p x}
#output
:a
:b
:c
Method to retrieve only value
python
obj = {:a=>1, :b=>2, :c=>3}
obj.each_value{|x| p x}
#output
1
2
3
Recommended Posts