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プログラムを作る練習

0
Last updated at Posted at 2023-06-14

任意の数字が配列の中の何番目に格納されているかを確認できるプログラムを作成したい。

memory = [2, 4 ,6 , 8, 12, 14, 16, 18, 20, 40, 60, 80, 88, 888, 88888888]

上のmemoryの配列から任意の数字を探して何番目に含まれているかという結果を返すsearchメソッドを、
each_with_indexを用いて作ろう♪(each_with_indexメソッドは、標準で組み込まれているメソッドの1つ。要素の繰り返し処理と同時に、その要素が何番目に処理されたのかも表すことができる。)

下のsearchメソッドとeach_with_indexメソッドの例を参考に作成しよう。

def search(num, output)
  # 処理を記述
end

output = [1, 5, 10 ,15, 20, 21, 29, 35, 42, 51, 62, 78, 81, 90, 92, 100]
# 呼び出し例
search(5, output) #2番目にあります

each_with_indexメソッドの使い方

配列名.each_with_index  do |item, i|

end

each_with_indexの具体例。

domestic_cars= ["HONDA","LEXUS","TOYOTA","MATSUDA","SUZUKI"]

domestic_cars.each_with_index do |car, n|
 puts "#あなたが{n}番目に大好きな車は、#{car}です。"
end

これを実行すると

あなたが0番目に大好きな車はHONDAです
あなたが1番目に大好きな車はLEXUSです
あなたが2番目に大好きな車はTOYOTAです

と出力される。

では上のSEACHメソッドとeach_with_indexの例を参考に、

memory = [2, 4 ,6 , 8, 12, 14, 16, 18, 20, 40, 60, 80, 88, 888, 88888888]

memoryの任意の数字を探して何番目に含まれているかという結果を返すsearchメソッドをeach_with_indexメソッドを用いて作ってみよう。

def search(correct_num, memory)

 memory.each_with_index do |num, index|
    if num == correct_num
      puts "#{index + 1}番目にありました!!!"
      return
    end
  end
  puts "その数は含まれておりませんでした。"
end

memory = [2, 4 ,6 , 8, 12, 14, 16, 18, 20, 40, 60, 80, 88, 888, 88888888]

search(703, memory)

こうなる。

今回は memoryの配列に703が含まれてないので、
実行すると、その数は含まれておりませんでした。
と出力される。

まず、memory.each_with_indexでは、memoryに格納されている要素を1つひとつnumとして取り出すと同時に、要素毎に割り当てられている添字をindexとして取得する。

次に、次に、if文でnum == correct_numという条件式を設定する。
ここでは、memoryから取り出された要素numと、correct_numが等しいかを判別してる。

そして、numとcorrect_numが等しければ、numがmemoryの中の何番目に含まれているかが出力される。

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?