0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

indexメソッドのまとめ

0
Last updated at Posted at 2023-06-22
index(pattern, pos = 0) -> Integer | nil

文字列のインデックス pos から右に向かって pattern を検索し、最初に見つかった部分文字列の左端のインデックスを返します。見つからなければ nil を返します。

引数 pattern は探索する部分文字列または正規表現で指定します。

pos が負の場合、文字列の末尾から数えた位置から探索します。

[PARAM] pattern:
探索する部分文字列または正規表現
[PARAM] pos:
探索を開始するインデックス



p "astrochemistry".index("str")         # => 1
p "regexpindex".index(/e.*x/, 2)        # => 3
p "character".index(?c)                 # => 0

p "foobarfoobar".index("bar", 6)        # => 9
p "foobarfoobar".index("bar", -6)       # => 9

(上記事項は Ruby3.2リファレンスマニュアルより引用しています。)

そして、文字列の先頭から検索を開始する場合、第二引数は省略が可能です。

なので、

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

を、省略してこう書けます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?