开发者

strpos() in Ruby?

开发者 https://www.devze.com 2023-02-20 12:15 出处:网络
In PHP there\'s a useful strpos function that finds the position of 开发者_如何学Cfirst occurrence of a string.

In PHP there's a useful strpos function that finds the position of 开发者_如何学Cfirst occurrence of a string. Is there a similar way to do this in Ruby?


str.index(pattern)

Use the index() method. This will return the index if found, otherwise return nil.

Usage:

ruby-1.9.2-p136 :036 > str = "Ruby is awesome"
 => "Ruby is awesome" 
ruby-1.9.2-p136 :037 > str.index("is awesome")
 => 5 
ruby-1.9.2-p136 :038 > str.index("testtest")
 => nil 


you can try

>> "abc".index("b")
=> 1

or

>> "acdfeb".match("f").begin(0)
=> 3
0

精彩评论

暂无评论...
验证码 换一张
取 消