Why Array#length is better than Array#size
Posted by James Mead Tue, 07 Aug 2007 17:05:00 GMT
Recently Luke and I spotted a subtle bug in our code where we were mistakenly assuming a method returned an Array when it actually returned a Fixnum. We were then calling the #size method on the result, but interestingly Fixnum#size returns the number of bytes in its machine representation.
Previously I had noticed that my colleague Paul Battley tended to use Array#length in preference to Array#size. Now I know why, or at least I know why I’m going to start using Array#length! If we’d used #length in this case we would have seen a NoMethodError instead of the spurious value, 4.
[5,6].size # => 2
1.size # => 4
[5,6].length # => 2
1.length # => NoMethodError: undefined method `length' for 1:FixnumUpdate: Josh Susser has posted a useful related article about the use of…

Hello, What’s wrong with
[5,6]is_a? Array #=> true6.is_a? Array #=> false? Dave
...or rather why do you prefer
length?Hmm, is this an argument for strict type checking, or an problem arising from English semantics?
Dave: I don’t want to explicitly check that the object is an array, because I’m assuming it is an array. But on the offchance it isn’t I’d prefer it to fail fast and not give me a dodgy value.