Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 2.2.1 - string.each_char is not giving unique indices for reoccurring letters - how do I do that?

Tags:

ruby

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.

like image 342
ThothLogos Avatar asked Jun 04 '15 03:06

ThothLogos


2 Answers

.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
like image 72
Amadan Avatar answered Sep 22 '22 20:09

Amadan


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
like image 32
14 revs, 12 users 16% Avatar answered Sep 24 '22 20:09

14 revs, 12 users 16%