LoginSignup
0
0

More than 1 year has passed since last update.

indexメソッド

Posted at

indexメソッド

文字列や配列の中に、指定した文字列が含まれていたとき、その文字列が何番目から配置されているのかを整数の値で返します。

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

indexメソッドの公式リファレンスはこちら。

https://docs.ruby-lang.org/ja/latest/method/String/i/index.html

indexメソッドを使ってプログラムを作成します

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

呼び出し・出力例は以下のような形で行います。
count_code("codexxcode") → 1(ターミナルの返し)
count_code("aaacodebbb") → 4(ターミナルの返し)
count_code("cozexxcode") → 7(ターミナルの返し)

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

呼び出し例
count_code("codexxcode")

解説

indexメソッドは文字列の先頭を0番目から数えて返します。
そのため、検索を開始する位置を+1して、1番目からカウントしてもらうように記述しています。

模範解答例として、以下でもプログラムは実行できます。
第二引数である0を省略して記述したものが上記で書いたものです。

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