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 3 years have passed since last update.

each_with_indexを使用したプログラムを作成する問題

Posted at

問題

以下の配列から任意の数字を探して何番目に含まれているかという結果を返すsearchメソッドを、each_with_index
を用いて作成するという問題。

input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]

出力例

search(5, input) → 2番目にあります

search(12, input) → 4番目にあります

search(7, input) → その数は含まれていません

まず、each_with_indexがわからないので理解します。

each_with_indexメソッドとは

配列名.each_with_index  do |item, i|

end

fruits = ["メロン", "バナナ", "アップル"]

fruits.each_with_index do |item, i|
 puts "#{i}番目のフルーツは、#{item}です。"
end

出力結果

0番目のフルーツはメロンです
1番目のフルーツはバナナです
2番目のフルーツはアップルです

とりあえず、書いてみる。

def search(target_num, input)
  input.each_with_index do |num, i|
    puts "#{i}番目にあります。"
   end
end

input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
search(5, input)

出力結果

0番目にあります
1番目にあります
2番目にあります
3番目にあります
4番目にあります
5番目にあります
6番目にあります
7番目にあります
8番目にあります
9番目にあります
10番目にあります
11番目にあります
12番目にあります
13番目にあります
14番目にあります
15番目にあります

意図した結果とかなり違います。

失敗を分析して次に活かします。

  • 数値がない場合は「ありません」を返すのでif文を使ってみる。
  • each doで配列を全部表示してしまっているのでreturnで止めてみる。

書いてみる。(2回目)

こういうこと?

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

input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
search(5, input)

出力結果

1番目にあります

1番目にはないんです。

ということは if num == input[i]がまずそうです。

returnで止まったのはよかった。

”5”と”num”が同じになったところで表示してほしい・・・

また書いてみる

・仮引数と実引数の値の受け渡しがよくわからないので、困ったらbinding.pry

 ・・・エラー。どうやらrailsでしか使えない?

  • binding.pryが使えないなら、putsで直接出力してみる。

結果

puts target_num   5
puts num  3

なるほど、target_numは仮引数からの引き継ぎ?でメソッドの中でも”5”、numは配列の一つ目の値”3”ということ。

ということは numtarget_numがイコールでif文を作ればいいんですかね。

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

input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
search(5, input)

出力結果

その数は含まれていません
2番目にあります

余計な表示が出てる・・・

elseがいらない?

配列の中を探してもイコールの値が見つからなかった結果が”含まれていない”だからeach分の外に表記?

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

出力結果

2番目にあります

こういうことですね!
スッキリしました!

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?