gpt4 book ai didi

ruby - 获取ruby中所有字符的索引

转载 作者:数据小太阳 更新时间:2023-10-29 08:17:09 25 4
gpt4 key购买 nike

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

    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

关于ruby - 获取ruby中所有字符的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32944759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com