0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rubyで配列処理

Posted at

each

単純な繰り返し処理

sample.rb
numbers = [1,2,3,4]
sum = 0
numbers.each do |num|
  sum += num
end
p sum # => 10

delete_if

配列を回し、各要素を評価。評価した結果、Trueだった要素を配列から削除する

sample.rb
# delete_if : 真を返すものを配列から削除する
numbers.delete_if do |num|
  num.odd? # 奇数の場合、真
end
p numbers # => [2, 4]

map

配列を回し各要素に対してブロック内の処理を実行。新しい配列を返す。
※Javaのstreamに似ている。
※元の配列には何の影響も与えない

sample.rb
new_numbers = numbers.map { |num| num * 10 } # 各要素にブロック内の処理を行い、新しい配列を生成する
p new_numbers # => [20, 40]
p numbers # => [2, 4]

select

配列を回し各要素を評価。評価した結果、Trueだった要素のみの配列を新たに返す

numbers = [1,2,3,4,5,6,7,8,9]
new_numbers = numbers.select { |num| num.even? } # 真になった要素のみの新しい配列を生成
p new_numbers # => [2, 4, 6, 8]

reject

select の逆の挙動

sample.rb
new_numbers = numbers.reject { |num| num.even? } # 真になった要素を取り除いた新しい配列を生成
p new_numbers # => [1, 3, 5, 7, 9]

find

配列を回し、各要素を評価し、Trueになった最初の要素のみ返す

sample.rb
new_numbers = new_numbers.find { |num| num % 3 == 0 } # 真になった最初の要素を返す
p new_numbers # => 3

inject

sample.rb
new_numbers =  numbers.inject(100) { |result, num| result + num }
p new_numbers # 100+1+2+3+4+5+6+7+8+9 = 145
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?