Shilpi Agrawal
Shilpi Agrawal

Reputation: 615

Get the index of all characters in ruby

I am trying to get the index of string which has duplicate characters. But if I have same characters it keeps returning the index of first occurrence of that character

    str = "sssaadd"

    str.each_char do |char|
       puts "index: #{str.index(char)}"
    end

Output:-
index: 0
index: 0
index: 0
index: 3
index: 3
index: 5
index: 5

Upvotes: 2

Views: 3771

Answers (3)

Aleksey Shein
Aleksey Shein

Reputation: 7482

If you want to find all indices of duplicated substrings, you can use this:

'sssaadd'.enum_for(:scan, /(.)\1/).map do |match| 
  [Regexp.last_match.begin(0), match.first]  
end
# => [[0, "s"], [3, "a"], [5, "d"]]

Here we scan all the string by regex, that finds duplicated characters. The trick is that block form of scan doesn't return any result, so in order to make it return block result we convert scan to enumerator and add a map after that to get required results.

See also: ruby regex: match and get position(s) of

Upvotes: 3

Arvind Kumar
Arvind Kumar

Reputation: 247

You also use this

  str = "sssaadd"

  arr=str.split('')

  arr.each_with_index do|char,index|
     puts "index : #{index}"
  end

Upvotes: 1

Amadan
Amadan

Reputation: 198496

Use Enumerator#with_index:

str = "sssaadd"
str.each_char.with_index do |char, index|
  puts "#{index}: #{char}"
end

Upvotes: 7

Related Questions