Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return index of all occurrences of a character in a string in ruby

Tags:

I am trying to return the index's to all occurrences of a specific character in a string using Ruby. A example string is "a#asg#sdfg#d##" and the expected return is [1,5,10,12,13] when searching for # characters. The following code does the job but there must be a simpler way of doing this?

def occurances (line)    index = 0   all_index = []    line.each_byte do |x|     if x == '#'[0] then       all_index << index     end     index += 1   end    all_index end 
like image 234
Gerhard Avatar asked Nov 30 '09 12:11

Gerhard


People also ask

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

The string. index() method is used to get the index of any character in a string in Ruby. This method returns the first integer of the first occurrence of the given character or substring.

How do you find the index of all occurrences in a string?

1. Using indexOf() and lastIndexOf() method. The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.

What is rindex in Ruby?

Ruby | Array rindex() function Array#rindex() : rindex() is a Array class method which returns the index of the last object in the array. Syntax: Array.rindex() Parameter: Array. Return: the index of the last object in the array.

How do I use GSUB in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.


2 Answers

s = "a#asg#sdfg#d##" a = (0 ... s.length).find_all { |i| s[i,1] == '#' } 
like image 141
FMc Avatar answered Sep 20 '22 17:09

FMc


require 'enumerator' # Needed in 1.8.6 only "1#3#a#".enum_for(:scan,/#/).map { Regexp.last_match.begin(0) } #=> [1, 3, 5] 

ETA: This works by creating an Enumerator that uses scan(/#/) as its each method.

scan yields each occurence of the specified pattern (in this case /#/) and inside the block you can call Regexp.last_match to access the MatchData object for the match.

MatchData#begin(0) returns the index where the match begins and since we used map on the enumerator, we get an array of those indices back.

like image 28
sepp2k Avatar answered Sep 21 '22 17:09

sepp2k