Home > Net >  Why is the method #each_index non existing for hashes in Ruby?
Why is the method #each_index non existing for hashes in Ruby?

Time:07-29

Why can I use #each and #each_with_index on both arrays and hashes, but the #each_index method can be used only on an array and not on a hash?

CodePudding user response:

each_index

Iterates over array indexes.

Hashes don't have indexes. Hashes have keys. Use each_key.

Why do Hashes have each_with_index? Because that's part of the Enumerable module which both Hashes and Arrays include. Enumerable methods use shared terminology. Hashes and Arrays predate the Enumerable module, Array#each_index (sometime before v1.0r2) came before Enumerable#each_with_index (Feb 5th, 1998), so there is some overlap between Array, Hash, and Enumerable for backwards compatibility.

  • Related