Jane
Jane

Reputation: 39

Ruby Enumerables -- what are they exactly?

Can someone explain in the most basic, laymans terms what a Ruby Enumerable is? I'm very new to coding and just starting to work with arrays and hashes. I read the word "Enumerables" everywhere but I don't understand what they are.

Upvotes: 1

Views: 344

Answers (2)

7stud
7stud

Reputation: 48589

Can someone explain in the most basic, laymans terms what a Ruby Enumerable is?

It's a module that defines a bunch of methods, and when another class includes that module, those methods are available in that class. So if someone uses a method like each_with_index on an Array, and you say to yourself, "I wonder how that method works. I'll check the Array docs.", you won't find that method in the Array docs. When you are searching for a method definition, and you can't find it in the Array docs, you need to examine the Array docs to see what modules are included by the Array class; then you will see that Array includes Enumerable. So you can click the Enumerable link, and there you will find the definition for each_with_index. Try it.

I think what you really mean is: What is an Enumerator?

And an Enumerator is a thing that can step through(i.e. iterate) the elements of a collection(Array, Hash, etc.). However, if you just started coding, the only thing you need to worry about is how to find the definitions of methods in the docs, and hopefully the above will sort that out. Enumerators are out on the horizon of your future.

Upvotes: 1

Dean Brundage
Dean Brundage

Reputation: 2048

From the docs:

The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection.

Upvotes: 0

Related Questions