LoginSignup
0
0

More than 1 year has passed since last update.

Ruby 配列を使ったプログラムの作成

Posted at

each_with_index

each_with_indexはRubyに標準で組み込まれているメソッドです。
繰り返し処理をしながら、その要素が何番目に処理されたのか、表示することができます。

配列名.each_with_index  do |item, i|

end

animals = ["ねこ", "とり", "うさぎ"]

animals.each_with_index do |animal, i|
  puts "#{i + 1}番目の動物は、#{animal}です"
end
1番目の動物は、ねこです
2番目の動物は、とりです
3番目の動物は、うさぎです
# ターミナル出力

配列は0番目から始まるため、#{i + 1}としています。

searchメソッドとeach_with_indexメソッドを組み合わせてプログラムを作る

def search(target_num, input)

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

input = [2, 4, 6 ,8, 10, 12, 14, 16, 18, 20]
search(10, input)

↓配列inputを定義しています。

input = [2, 4, 6 ,8, 10, 12, 14, 16, 18, 20]

↓searchメソッドを呼び出しています。10と変数inputは実引数。
search(10, input)

1行目、呼び出されたsearchメソッドでは、target_numとinputを借り引数として受け取ります。

input.each_with_index〜内での処理
配列inputに格納されている要素を1つ一つnumとして取り出し、要素ごとに当てられている添字をindexで取得します。
if文でnumとtarget_numが等しいと、「○番目にあります」とターミナルで出力されます。
returnでそのメソッドを終わらせます。

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