2

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
Shilpi Agrawal
  • 595
  • 3
  • 11
  • 26
  • 1
    Are you trying to always get all characters plus their index position as the end result? Or get something more general (i.e. a method that tells you position of the 5th 'z' in a string, or a method that if passed a string and a character, gives you all index positions of that character)? It may be worth showing an imagined function that returns what you want . . . – Neil Slater Oct 05 '15 at 09:06

3 Answers3

7

Use Enumerator#with_index:

str = "sssaadd"
str.each_char.with_index do |char, index|
  puts "#{index}: #{char}"
end
Amadan
  • 191,408
  • 23
  • 240
  • 301
3

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

Community
  • 1
  • 1
Alexey Shein
  • 7,342
  • 1
  • 25
  • 38
1

You also use this

  str = "sssaadd"

  arr=str.split('')

  arr.each_with_index do|char,index|
     puts "index : #{index}"
  end
Arvind Kumar
  • 237
  • 3
  • 11