[Ruby] Difference between each method and for statement. The elements are taken out one by one and processed.

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.

table of contents

  1. Difference between each method and for statement
  2. each method syntax
  3. When the target is a range object (#対象がrangeオブジェクトの場合)
  4. When the target is an array
  5. If the target is a hash
  6. When there is one argument
  7. When there are two arguments
  8. each_pair, each_key, each_value methods
  9. each_pair method
  10. each_key method
  11. each_value method

## Difference between each method and for statement The processing content is the same as the for statement. The difference from the for statement is ** variable scope **.
** ▼ Difference in scope ** ** The difference between a variable being valid only during processing and being valid outside **.

--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)


** ▼ When the target is a range object ** If you specify a range object `..` or` ... `as an object, each must be enclosed in parentheses (see below).
## syntax of each method

object.each {|variable|processing} ┗ Object is iterable ┗Variable contains each extracted value ┗ {} is called ** block **

block{}Isdo |variable|Processing endSame 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

## When the target is a range object If the target is a range object, enclose it in parentheses.

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.


** ▼ Error ** If you do not enclose it in parentheses, an error will occur.

python


1..3.each{|x| p x}
NoMethodError (undefined method `each' for 3:Integer)

** ▼ Assign to variable ** Any variable to which the range object is assigned can be specified as it is.

python


range1 = 1..3
range1.each{|x| p x}

##output
1
2
3

** ▼ For statement ** In the case of a for statement, it works without parentheses.

python


for x in 1..3
  p x
end

##output
1
2
3

## When the target is an array

python


arr = [1, 2, 3]
arr.each{|x| p x}

##output
1
2
3

Of course, arr remains the same after processing.


## If the target is a hash In the case of hash, the elements that can be acquired differ depending on the number of variables specified.
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 If there is one argument, the array of keys and values ​​is fetched one by one.

When there is one argument


obj = {:a=>1, :b=>2, :c=>3}
obj.each{|x| p x}

##output
[:a, 1]
[:b, 2]
[:c, 3]

### When there are two arguments If there are two arguments, the first argument is the key and the second argument is the value.

** ▼ 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

## each_pair, each_key, each_value methods As for the method of getting the key and value of the hash, each method is prepared in addition to being specified by the variable of each method.

(1) each_pair method

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]

(2) each_key method

Method to retrieve only key

python


obj = {:a=>1, :b=>2, :c=>3}
obj.each_key{|x| p x}

#output
:a
:b
:c

(3) each_value method

Method to retrieve only value

python


obj = {:a=>1, :b=>2, :c=>3}
obj.each_value{|x| p x}

#output
1
2
3

It seems that there is no need to use the each_xxx method in particular, as it can be determined by the number of variables in each method and the specification method.

Recommended Posts

[Ruby] Difference between each method and for statement. The elements are taken out one by one and processed.
Easy to understand the difference between Ruby instance method and class method.
[Ruby] I thought about the difference between each_with_index and each.with_index
About the difference between classes and instances in Ruby
About the difference between "(double quotation)" and "single quotation" in Ruby
[Ruby] About the difference between 2 dots and 3 dots of range object.
Let's override the difference between == (identity) and equals method (equivalence)
The difference between programming with Ruby classes and programming without it
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
[Ruby] Difference between get and post
Difference between instance method and class method
Difference between render method and redirect_to
Difference between == operator and equals method
[Ruby] Difference between is_a? And instance_of?
Difference between == operator and eqals method
Understand the difference between each_with_index and each.with_index
The value is taken out from the double hash and output by the getter.
[Rails] I studied the difference between new method, save method, build method and create method.
Note: Difference between Ruby "p" and "puts"
Difference between Ruby instance variable and local variable
[For beginners] Difference between Java and Kotlin
About the difference between irb and pry
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
[Ruby] What is the slice method? Let's solve the example and understand the difference from slice!
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.