3 ms·
"Looping over a collection object requires some knowledge of its internal state (length in the case of a simple linear structure like Array). In most cases wher
by protomyth 14y ago
"Looping over a collection object requires some knowledge of its internal state (length in the case of a simple linear structure like Array). In most cases where we use for loops, that information isn't really relevant. There is no need to expose it to the outside world and break encapsulation."
The examples from the article don't make me think I need length or any other internal knowledge to use the for..in loop as opposed to each.
- jasim 14y agoMy bad, sorry. The 'for..in' construct does not require you to expose the length of the structure. However, the other argument still holds true: In case of a user-defined collection object, 'for..in' will not work since the underlying collection will be hidden.
- cdcarter 14y agoIn Ruby "for...in" is just syntactic sugar for #each. Try defining your own #each on a random object!
- roryokane 14y agoUnder the hood, 'for..in' just calls #each. Therefore, it is easy to make 'for..in' work with a custom collection: just define #each. And that is what you would do anyway if you were defining an Enumerable custom collection.