LoginSignup
0
0

More than 1 year has passed since last update.

indexメソッドを使って検索

Posted at

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

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

ヒント: indexメソッドを使用

indexメソッドとは

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

str.index(検索したい文字列, [検索を開始する位置])
解答
def count_code(str)
  puts str.index("code", 0) + 1
end

count_code("codexxcode")
ターミナル
1

+1を記述しなかった場合、ターミナルでは0が返ってきます。
文字列の先頭を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