Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strpos() in Ruby?

Tags:

ruby

strpos

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?

like image 682
Mark Avatar asked Mar 30 '11 02:03

Mark


People also ask

What is the strpos () function used for?

The strpos() function finds the position of the first occurrence of a string inside another string.

What does Strpos return?

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.


1 Answers

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 
like image 70
Mike Lewis Avatar answered Oct 04 '22 09:10

Mike Lewis