At least in Ruby 1.9.3, Enumerable
objects do not have a length
attribute. Why is this?
Enumerable has the count
method, which is usually going to be the intuitive "length" of the enumeration.
But why not call it "length"? Well, because it operates very differently. In Ruby's built-in data structures like Array
and Hash
, length
simply retrieves the pre-computed size of the data structure. It should always return instantly.
For Enumerable#count
, however, there's no way for it to know what sort of structure it's operating on and thus no quick, clever way to get the size of the enumeration (this is because Enumerable
is a module, and can be included in any class). The only way for it to get the size of the enumeration is to actually enumerate through it and count as it goes. For infinite enumerations, count
will (appropriately) loop forever and never return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With