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


i'm confused behavior of each_char, i'm trying iterate through string , unique, specific index each character in string. ruby seems not iterate on every discrete character, rather 1 copy of given character populates string.

def test(string)   string.each_char |char|     puts string.index(char)   end end  test("hello") test("aaaaa") 

produces 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 general form of #each in other contexts. expect indices "aaaaa" 0, 1, 2, 3, 4 - how can achieve behavior?

i looked @ official documentation string , doesn't seem include method behaves way.

.each_char giving every "a" in string. each "a" identical - when you're looking "a", .index give first 1 finds, since can't know you're giving it, say, third one.

the way not char find index (because can't, given above), index along char.

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

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -