获取ruby中所有字符的索引

Get the index of all characters in ruby

我正在尝试获取具有重复字符的字符串的索引。但是如果我有相同的字符,它会不断返回第一次出现该字符的索引

    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

使用Enumerator#with_index:

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

你也用这个

  str = "sssaadd"

  arr=str.split('')

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

如果你想找到重复子串的所有索引,你可以使用这个:

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

这里我们scan 正则表达式查找重复字符的所有字符串。诀窍是 scan 的块形式不会 return 任何结果,因此为了使其成为 return 块结果,我们将 scan 转换为枚举器并添加一个 map 之后获得所需的结果。

另请参阅:ruby regex: match and get position(s) of