Ruby Enumerables — what are they exactly?

只谈情不闲聊 提交于 2020-01-03 02:04:36

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26227668/ruby-enumerables-what-are-they-exactly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!