LoginSignup
0
0

More than 1 year has passed since last update.

each_with_indexを使ったプログラム

Last updated at Posted at 2022-09-18

each_with_indexメソッド

eachメソッドは配列の要素を一つずつ取り出せるものの、取り出す要素が何番目のものかを取得することはできない。
each_with_indexメソッドなら要素の繰り返し処理と同時にその要素が何番目に処理されたものなのかも同時に取得できる。

使い方の例

配列データ.each_with_index do |x, i|
    処理内容
end

each_with_indexメソッドはブロック変数がeachメソッドより一つ多い。
変数xは配列の各要素、変数iは配列の順序(インデックス)となる。
インデックスは0から始まる整数で要素が増える毎に1ずつ増える。

サンプル

下記のような配列データから任意の数字を探して何番目に含まれているかと言う結果を返すsearchメソッドをeach_with_indexメソッドを使って作成する。

input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
sample.rb
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 = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
search(11, input)

searchメソッドを呼び出す処理

配列inputを定義。次にsearchメソッドを呼び出し、実引数としてsearch(11, input)をセット。

searchメソッド内の処理

input.each_with_index do |num, index| はinputに格納された要素を一つ一つnumで取り出し、要素ごとに割り当てられている添字をindexとして取得する。

次にif num == target_numと言う条件式を設定。
ここではinputから取り出された要素numとtarget_numが等しいかを判別している。
numとtarget_numが等しければ、numがinputの中の何番目に含まれているかが出力される。
#{index + 1}としているのは配列の添字が0から始まるため。

出力結果

今回の場合は仮引数で設定した11だとinputの配列の中にある数字とは等しくないので結果は以下のようになる。
search(11, input) # 出力:"11は含まれていません"

もし12など配列の中の数字と等しい場合は以下のようになる。
search(12, input) # 出力:"12は4番目にあります"

0
0
4

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