Ruby indexメソッド
indexメソッドindexメソッドは、文字列や配列の中に指定した文字列が含まれていた場合、その文字列の開始位置を整数の値で返すメソッドです。
任意の文字列に"code"が、左から何文字目に出てくるかを返し、その数を出力するメソッドを作りましす。
def count_code(str) puts str.index("code",0)+1 #index(検索したい文字列, 検索を開始する位置) end #先頭を0から数える為、+1をしています count_code("codexxcode") count_code("aaacodebbb") count_code("cozexxcode")