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

时间:2015-06-04 03:48:44

标签: ruby

我对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的官方文档,它似乎没有包含一种行为方式。

2 个答案:

答案 0 :(得分:12)

.each_char正在为您提供字符串中的每个"a"。但每个"a"都是相同的 - 当您正在寻找"a"时,.index会为您找到它找到的第一个,因为它无法了解您&#39}比如,第三个给它。

这样做的方法不是让char然后找到它的索引(因为你不能,如上所述),但是要获得索引以及char。

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

答案 1 :(得分:1)

index('a')将始终从字符串的开头开始,并返回找到的第一个匹配项。

你想要的是

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