How to find character index in string in Ruby?

For example, str = 'abcdefg' . How to find index if c in this line using Ruby?

+46
string ruby indexing
May 19 '12 at 19:52
source share
3 answers
 index(substring [, offset]) → fixnum or nil index(regexp [, offset]) → fixnum or nil 

Returns the index of the first occurrence of a given substring or pattern (regexp) in str. Returns nil if not found. If a second parameter is present, it indicates the position in the string to start the search.

 "hello".index('e') #=> 1 "hello".index('lo') #=> 3 "hello".index('a') #=> nil "hello".index(?e) #=> 1 "hello".index(/[aeiou]/, -3) #=> 4 

Check out ruby documents for more information.

+70
May 19 '12 at 20:02
source share

You can use this

 "abcdefg".index('c') #=> 2 
+21
May 19 '12 at 19:56
source share
 str="abcdef" str.index('c') #=> 2 #String matching approach str=~/c/ #=> 2 #Regexp approach $~ #=> #<MatchData "c"> 

Hope this helps. :)

+3
May 19 '12 at 20:50
source share



All Articles