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?
The strpos() function finds the position of the first occurrence of a string inside another string.
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With