An index identifies an element or its position, but what counts as an index depends on the collection. Arrays use consecutive numeric positions; hashes retrieve values by key. For strings, index searches for a substring and returns where its first occurrence begins. section 8.1.3 section 9.1
Ruby uses related terms for two different jobs:
- Use String#index to find a substring’s position; use rindex to find its first occurrence from the right. section 8.1.3
- Use each_with_index to pair each yielded item with an ordinal counter. This counter is not necessarily an index understood by the collection: hashes support it, but do not have each_index. section 10.5.2
>> string.index("cool")
=> 10
>> string.index("l")
=> 13
>> string.rindex("l")
=> 15
The search for “cool” returns position 10; searching for “l” from the right returns position 15. section 8.1.3
>> letters = {"a" => "ay", "b" => "bee", "c" => "see" }
=> {"a"=>"ay", "b"=>"bee", "c"=>"see"}
>> letters.each_with_index {|(key,value),i| puts i }
0
1
2
=> {"a"=>"ay", "b"=>"bee", "c"=>"see"}
>> letters.each_index {|(key,value),i| puts i }
undefined method 'each_index' for an instance of Hash (NoMethodError)
A hash can yield ordinal counters during each_with_index, but calling each_index on it raises an error. section 10.5.2














