liveBook · Manning

Indexing

As explained in The Well-Grounded Rubyist, Fourth Edition

An index is a numeric or key-based identifier for an element in a collection, including an ordinal position in an ordered collection.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Distinguishes string search positions, array indexes, hash keys, and iteration counters, including the absence of Hash#each_index.
Examples
Uses substring searches, numbered president lists, and hash iteration counters to illustrate indexing.
What you can do after
Apply indexing to locate substrings, retrieve collection entries, and label iterated items with their ordinal positions.
How it connects
Connects indexing to strings, arrays, hashes, Enumerable iteration, and enumerators.

Also explained in

Compare how 15 books explain indexing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.