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:Fixnum

Update: Josh Susser has posted a useful related article about the use of…

Tags , , , , , ,  | 4 comments

Comments

  1. Dave said about 16 hours later:

    Hello, What’s wrong with
    [5,6]is_a? Array #=> true
    6.is_a? Array #=> false
    ? Dave

  2. Dave said about 16 hours later:

    ...or rather why do you prefer length?

  3. Benjamin Kudria said 24 days later:

    Hmm, is this an argument for strict type checking, or an problem arising from English semantics?

  4. James Mead said 37 days later:

    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.

Comments are disabled