Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 353
Orcris Avatar asked May 19 '12 19:05

Orcris


People also ask

How do you find the index of a certain character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the substring of a string in Ruby?

There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.

What does .index do in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present.


2 Answers

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.

like image 156
kingasmk Avatar answered Sep 24 '22 01:09

kingasmk


You can use this

"abcdefg".index('c')   #=> 2 
like image 27
Mennan Avatar answered Sep 26 '22 01:09

Mennan