Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Enumerable not have a length attribute in Ruby?

At least in Ruby 1.9.3, Enumerable objects do not have a length attribute. Why is this?

like image 607
kdbanman Avatar asked Mar 03 '15 18:03

kdbanman


1 Answers

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.

like image 91
Max Avatar answered Nov 11 '22 08:11

Max