How do I find the index of a character in a string in Ruby? How do I find the index of a character in a string in Ruby? ruby ruby

How do I find the index of a character in a string in Ruby?


index(substring [, offset]) → fixnum or nilindex(regexp [, offset]) → fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin 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.


You can use this

"abcdefg".index('c')   #=> 2


str="abcdef"str.index('c') #=> 2 #String matching approachstr=~/c/ #=> 2 #Regexp approach $~ #=> #<MatchData "c">

Hope it helps. :)