LoginSignup
0
0

More than 3 years have passed since last update.

【初心者】Rubyの配列に対する繰り返し処理色々

Posted at

実行環境

超基本的な内容なので、実行環境に左右されないと思いますが、一応明記しておきます。
OS : macOS Catalina ver10.15.5
Ruby : 2.7.1p83

each

基本的な繰り返し処理。要素を一つづつ取り出して処理を行なっていく。
do ~ end で囲むのが基本。変数のスコープに注意。

sample.rb
numbers = [1, 2, 4, 5, 6]

total = 0
numbers.each do |num|
  total += num
end
p total # 18 

map

配列を返してくれることが特徴。下記の処理は要素に10を足して出力している。
簡単な処理ならばdo ~ end の代わりに { }で記入可能。

sample.rb
numbers = [1, 2, 4, 5, 6]

nuadd_num = numbers.map {|num| num + 10}

p add_num
# [11, 12, 14, 15, 16]

select

処理内の判定に合致した値を配列として返している。

sample.rb
numbers = [1, 2, 4, 5, 6]

numbers2 = numbers.select {|num| num % 2 == 0}

p numbers2
# [2, 4, 6]

reject

処理内の判定に合致しない値を配列として返している。selectの逆。

sample.rb
numbers = [1, 2, 4, 5, 6]

numbers2 = numbers.reject {|num| num % 2 == 0}

p numbers2
# [1, 5]

inject

たたみ込み処理。num と i にそれぞれ要素が代入され処理を行なっていく。

sample.rb
numbers = [1, 2, 4, 5, 6]

numbers2 = numbers.inject {|num, i| num + i}

# 1回目のループ num = 1, i = 2
# 2回目のループ num = 3, i = 4
# 3回目のループ num = 7, i = 5
# 4回目のループ num = 12, i = 6

p numbers2
# 18

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0