0
0

More than 1 year has passed since last update.

【Ruby】検索問題

Posted at

※初心者向け
※アウトプット練習の為
※学習の復習

開発環境
rails 6.0.4.4
ruby 2.6.5

問題

任意の文字列に"code"が、左から何文字目に出てくるかを返し、その数を出力するメソッドを作りましょう。

出力例:
count_code("codexxcode") → 1
count_code("aaacodebbb") → 4
count_code("cozexxcode") → 7

ヒント: indexメソッドを使用しましょう

index
indexメソッドは、文字列や配列の中に指定した文字列が含まれていた場合、その文字列の開始位置を整数の値で返します。

str.index(検索したい文字列, [検索を開始する位置])

解答

def count_code(str)
  puts str.index("code", 0) + 1
end

解説

indexメソッドは文字列の先頭を0から数えた数字を返すため、+1をしています。

また、文字列の先頭から検索を開始する場合、第二引数は省略が可能です。
そのため、下記のようにコードを書き換えることが可能です。

def count_code(str)
  puts (str.index("code") + 1)
end
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