1
1

More than 1 year has passed since last update.

【入門】Ruby eachメソッドの様々な使い方を具体的に紹介

Last updated at Posted at 2022-09-25

はじめに

今回は、Rubyに標準で組み込まれているeachメソッドについて、備忘録としてまとめます。

※おことわり※
基本的に学習内容のアウトプットです。
初学者であるため、間違い等あればご指摘いただけますと嬉しいです。

この記事の目的

Rubyに標準で組み込まれているeachメソッドについてアウトプット

この記事の内容

  1. each_with_index
  2. each.with_index
  3. eachの入れ子
  4. each_slice
  5. each_key
  6. each_value

1. each_with_index

eachメソッドと同様に、要素の繰り返し処理を行いつつ、その要素が何番目に処理されたものなのか表示するメソッドです。
eachでループを回しつつ、それぞれのデータ(要素)に番号を振りたい時などに使います。

  • 書き方
配列名.each_with_index do |item, index|

end
  • 基本的な書き方
#書き方①
foods = ["あんぱん", "メロンパン", "食パン"]

foods.each_with_index do |item, index|
 puts "#{index + 1}番目の食べ物は、#{item}です。"
end

#書き方② doとendを省略
foods.each_with_index { |item, index| puts "#{index + 1}番目の食べ物は、#{item}です。" }

# 返り値
1番目の食べ物は、あんぱんです。
2番目の食べ物は、メロンパンです。
3番目の食べ物は、食パンです。
  • 応用的な書き方
    任意の数字が配列の中の何番目に格納されているかを確認します。
    存在する場合、「○○は○番目にあります」と返し、存在しない場合は「その数は含まれていません」と返します。
def search(target_num, input)

  input.each_with_index do |num, index|
    if num == target_num
      puts "#{num}は、#{index + 1}番目にあります"
      return
    end
  end
  puts "その数は含まれていません"
end

input = [11, 39, 55, 49, 70]

search(11, input)

# 返り値
11は、1番目にあります

2. each.with_index

こちらはメソッドではなく、each + with_indexを組み合わせています。
上記のeach_with_indexは添字が0から始まりますが、 each.with_indexは開始したい番号を指定することができます。

  • 書き方
配列名.each.with_index(開始したい番号) do |item, index|

end
  • 具体的な書き方
foods = ["あんぱん", "メロンパン", "食パン"]

foods.each.with_index(20) do |item, index|
 puts "#{index}番目の食べ物は、#{item}です。"
end

# 返り値
20番目の食べ物は、あんぱんです。
21番目の食べ物は、メロンパンです。
22番目の食べ物は、食パンです。

3. eachの入れ子

以下の配列より、果物の名前とそれぞれの合計額が出力する。

fruits_price = [["apple", [200, 250, 220]], ["orange", [100, 120, 80]], ["melon", [1200, 1500]]]

#["apple", [200, 250, 220]という形で1つずつ取り出す
fruits_price.each do |fruit|
	#[200, 250, 220]という形で1つずつ取り出し、sumに自己代入する
    sum = 0
	fruit[1].each do |price|
		sum += price
	end
	puts "#{fruit[0]}の合計金額は#{sum}円です。"
end

# 返り値
appleの合計金額は670円です。
orangeの合計金額は300円です。
melonの合計金額は2700円です。

4. each_slice

配列の要素を指定した数に分割して出力する。
※分かりやすく出力するため、putsではなくpを使用しています。

fruits = ["apple", "orange", "melon", "grape", "cherry", "strawberry"]
fruits.each_slice(2) do |fruit|
  p fruit
end

# 返り値
["apple", "orange"]
["melon", "grape"]
["cherry", "strawberry"]

fruits.each_slice(3) do |fruit|
  p fruit
end

# 返り値
["apple", "orange", "melon"]
["grape", "cherry", "strawberry"]

5. each_key

配列と同様に、ハッシュをeach_keyメソッドを使ってループします。

hash = {one: 1, two: 2, three: 3}
hash.each_key {|key|  puts "#{key}"}

# 返り値
one
two
three

6. each_value

ハッシュのvalueを取り出したい時は以下のように記述します。

hash = {one: 1, two: 2, three: 3}
hash.each_value { |value| puts "#{value}"}

# 返り値
1
2
3
1
1
2

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