LoginSignup
0
1

More than 3 years have passed since last update.

searchとeach_with_indexの組み合わせ

Posted at

今日のドリルで登場した式。

def search(target_num, input)

  input.each_with_index do |num, index|
    if num == target_num
      puts "#{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(12, input)

これで「4番目にあります」の出力ができる。

一方で、

def search(target_num, input)

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

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

こちらはnextを使って、
4番目の12が出るまでif文内の処理が続く、というもの。

一応nextがなくても結果は同じだけど、
読みやすさを考えるとnextがあった方がいいのでは、と思った今日この頃。

この記述に関して昼前まで議論が絶えんかったな。
プログラミングの魅力の一つと言っていいのかもしれない。

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