gpt4 book ai didi

Ruby 2.2.1 - string.each_char 没有为重复出现的字母提供唯一索引 - 我该怎么做?

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

我对 each_char 的行为感到困惑,我试图遍历一个字符串并为该字符串中的每个字符获取唯一的、特定的索引。 Ruby 似乎不会遍历每个 离散字符,而是只遍历填充字符串的任何给定字符的一个副本。

def test(string)
string.each_char do |char|
puts string.index(char)
end
end

test("hello")
test("aaaaa")

产生结果:

2.2.1 :007 >   test("hello")
0
1
2
2
4

2.2.1 :008 > test("aaaaa")
0
0
0
0
0

在其他情况下,这似乎与#each 的一般形式有悖常理。我希望“aaaaa”的索引为 0、1、2、3、4 - 我怎样才能实现这种行为?

我查看了 String 的官方文档,它似乎没有包含以这种方式运行的方法。

最佳答案

.each_char 为您提供字符串中的每个 "a"。但是每个 "a" 都是相同的 - 当您正在寻找一个 "a" 时,.index 会为您提供它找到的第一个,因为它不知道你在给它,比如第三个。

这样做的方法不是获取 char 然后找到它的索引(因为你不能,鉴于上述),而是在获取 char 的同时获取索引。

def test(string)
string.each_char.with_index do |char, index|
puts "#{char}: #{index}"
end
end

关于Ruby 2.2.1 - string.each_char 没有为重复出现的字母提供唯一索引 - 我该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30634628/

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