5 ms·
It's Ruby though, where Array has "size", "length", and "count", all of which are equivalent. The programmer chooses which one they prefer based on the context
by jewel 4y ago
It's Ruby though, where Array has "size", "length", and "count", all of which are equivalent. The programmer chooses which one they prefer based on the context or their style or the phase of the moon.
Ruby inherits the Perl philosophy of "There's more than one way to do it". Compare with Python, and its "There should be one — and preferably only one — obvious way to do it."
It's true that it makes the compiler less elegant, but Ruby optimizes for the programmer at the expense of the compiler.
- scruple 4y agoEquivalent in output but not in implementation / performance. Does that matter? Not usually, no, but it depends.
- eloisius 4y agoNot exactly the same. It's been a while, but if I recall, count takes a predicate block so you can do things like `numbers.count { |n| n.even? }`
- vidarh 4y agoIt can also take an argument and will then return the count of the number of items which compares equal to the argument. "count" is only equivalent to "length" and "size" when called with no argument and no block, and should be slower for that case (it includes a comparison of arity and a call to rb_block_given_p() in MRI before it returns the array length).