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
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.
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.
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.
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.
s = "a#asg#sdfg#d##" a = (0 ... s.length).find_all { |i| s[i,1] == '#' }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With