strpos() in Ruby?
Asked Answered
A

2

16

In PHP there's a useful strpos function that finds the position of first occurrence of a string. Is there a similar way to do this in Ruby?

Aceae answered 30/3, 2011 at 2:7 Comment(0)
N
30
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 
Natatorial answered 30/3, 2011 at 2:9 Comment(0)
S
1

you can try

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

or

>> "acdfeb".match("f").begin(0)
=> 3
Spic answered 30/3, 2011 at 2:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.