Why Array#length is better than Array#size
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:Fixnum
Update: Josh Susser has posted a useful related article about the use of…