Enumerables are not guaranteed to have lengths - the only requirement for an object which Enumerable is mixed into is that it responds to #each
, which causes it to return the next item in the series, and #<=>
which allows comparison of values provided by the enumerable. Methods like #sort
will enumerate the entire collection over the course of sorting, but may not know the bounds of the set ahead of time. Consider:
class RandomSizeEnumerable
include Enumerable
def each
value = rand 1000
while value != 500
yield value
value = rand 1000
end
end
# Not needed for this example, but included as a part of the Enumerable "interface".
# You only need this method if #max, #min, or #sort are used on this class.
def <=>(a, b)
a <=> b
end
end
This enumerable will be called until the iterator generates the value "500", which will cause it to stop enumerating. The result set is collected and sorted. However, a #length
method is meaningless in this context, because the length is unknowable until the iterator has been exhausted!
We can call #length
on the result of things like #sort
, since they return an array, though:
p RandomSizeEnumerable.new.sort.length # 321
p RandomSizeEnumerable.new.sort.length # 227
p RandomSizeEnumerable.new.sort.length # 299
Conventionally, #length
is used when the length is known and can be returned in constant time, whereas #count
(and sometimes #size
) tend to be used when the length may not be known ahead of time and needs to be computed by iterating the result set (thus, taking linear time). If you need the size of the result set provided by an Enumerable, try using .to_a.length
#count
.
Enumerable
module has been mixed in? Such classes (and others) have alength
(akasize
) method. – Cary Swoveland Mar 3 '15 at 18:25Enumerable#count
. – cremno Mar 3 '15 at 18:32length
method, I failed to mention that I was referring to built-in classes, but even of that I am now unsure. Does anyone know of a built-in class that mixes inEnumerable
that does not have alength
method? – Cary Swoveland Mar 3 '15 at 18:59Integer
,Numerica
,Proc
,CSV
,Matrix
), perhaps a class defininglength
is an exception rather than a rule. – Cary Swoveland Mar 3 '15 at 19:42Set
is enumerable, but not ordered. The reason it still makes sense to call#sort
on a set is because the return value is ordered (it's anArray
, as the docs forEnumerable
indicate). – gregates Mar 3 '15 at 22:04