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

RubyStringIndexing

Ruby Problem Overview


For example, str = 'abcdefg'. How do I find the index if c in this string using Ruby?

Ruby Solutions


Solution 1 - Ruby

index(substring [, offset]) → fixnum or nil
index(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.

Solution 2 - Ruby

You can use this

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

Solution 3 - Ruby

str="abcdef"

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

Hope it helps. :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOrcrisView Question on Stackoverflow
Solution 1 - RubykingasmkView Answer on Stackoverflow
Solution 2 - RubyMennanView Answer on Stackoverflow
Solution 3 - RubykiddorailsView Answer on Stackoverflow