I'm confused by the behavior of each_char, I'm trying to iterate through a string and get the unique, specific index for each character in that string. Ruby seems to not iterate over every discrete character, but rather only one copy of any given character that populates 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 it doesn't seem to include a method that behaves this way.
.each_char
is giving you every "a"
in your string. But each "a"
is identical - when you're looking for an "a"
, .index
will give you the first one it finds, since it can't know you're giving it, say, the third one.
The way to do this is not to get the char then find its index (because you can't, given the 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')
will always start from the beginning of the string, and return 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With