Ruby 2.2.1 - string.each_char does not give unique indices for repeated letters - how to do this?
I am confused by the behavior of each_char, I am trying to iterate over a string and get a unique, defined index for each character in that string. Ruby doesn't seem to iterate over every discrete character, but rather just one copy of any given character that fills the string.
def test(string)
string.each_char do |char|
puts string.index(char)
end
end
test("hello")
test("aaaaa")
Produces the result:
2.2.1 :007 > test("hello")
0
1
2
2
4
2.2.1 :008 > test("aaaaa")
0
0
0
0
0
This seems counter intuitive to the general form of #each in other contexts. I expect the indices for "aaaaa" to be 0, 1, 2, 3, 4 - how can I achieve this behavior?
I looked at the official documentation for String and don't seem to include a method that behaves this way.
.each_char
gives you each "a"
in your line. But each "a"
is identical - when you search "a"
, it .index
will give you the first one that it finds, since it cannot know that you are giving it to, say, the third.
The way to do this is not to get the char, then find its index (because you can't given above), but to get the index along with the char.
def test(string)
string.each_char.with_index do |char, index|
puts "#{char}: #{index}"
end
end
index('a')
always starts at the beginning of the line and returns the first occurrence found.
What you want is something like
def test(string)
string.each_char.with_index do |item, index|
puts "index of #{item}: #{index}"
end
end