LoginSignup
0
0

More than 1 year has passed since last update.

Ruby 問題⑩ 配列を利用したrubyプログラム作成

Last updated at Posted at 2021-06-03

はじめに

毎日投稿(土日除く)を始めて早1ヶ月。
少しづつ身になっている事を感じてきました。

本日も問題を解いていきます。

問題

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

input = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 30, 40, 50, 60, 70 ,80]
def search(target_num, input)
  # 記述
end

input = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 30, 40, 50, 60, 70 ,80]

# 例
search(11, input)

ヒント

each_with_indexメソッドを使う

each_with_indexとはrubyに標準に組み込まれているメソッドの1つです。

eachメソッドでは繰り返し処理をするのに使われていましたが、処理された要素は何番目に処理されたかは分かりません。そこでこのメソッドを使います。

配列名.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, index|
    if num == target_num
        puts "#{i + 1}番目にあります"
    end
  end
  puts "その数は含まれません"
end

input = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 30, 40, 50, 60, 70 ,80]

search(3, input)

配列inputを定義し、searchメソッドに実引数をしてセットします。
呼び出されたsearchメソッドでは、仮引数としてtarget_numとinputとして受け取リます。

#今回はtarget_numに3が入り、inputには配列が入っています
def search(target_num, input)

end

input = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 30, 40, 50, 60, 70 ,80]

search(3, input)

searthメソッド内の処理でinput.each_with_indexを使い、inputに格納されている要素をnumとして取り出し、要素毎に割り当てられた添字をindexとして取得します。

#numには配列に格納された要素
def search(target_num, input)
  input.each_with_index do |num, index|
   puts num
  end
end

input = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 30, 40, 50, 60, 70 ,80]

search(3, input)

# =>
2
4
6
8
10
12
14
16
18
20
30
40
50
60
70
80
#indexには添字
def search(target_num, input)
  input.each_with_index do |num, index|
   puts index
  end
end

input = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 30, 40, 50, 60, 70 ,80]

search(3, input)

# =>
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

target_numとnumの配列に一緒の要素が出た時に出力したいのでifを使います。

 if num == target_num
  puts "#{i + 1}番目にあります"
 end
  puts "その数は含まれません"

#{i + 1}としているのは配列は0番目から始まるので+1をしました。

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