Vass
Vass

Reputation: 2820

In Ruby are there absolutely no differences between 'size' and 'length'?

In the documentation for size, we can read here, that 'size() is an alias for length'. For length (doc) "Returns the number of elements in self. May be zero." and that length "Also aliased as: size". The functionality may be very similar, but I wonder if the different implementations contain any other features other than returning the number of elements in an array or collection. The words length and size seem to imply a difference, especially as size would direct me to think of size of memory in bytes rather than number of elements.

Upvotes: 3

Views: 234

Answers (2)

Arturo Herrero
Arturo Herrero

Reputation: 13122

It's exactly the same implementation.

You can see in the source code of Ruby 2.3.1 that is an alias:

rb_define_alias(rb_cArray,  "size", "length");

Also if you check with pry and pry-doc, you can see that it's executing exactly the same code:

[1] pry(main)> list = [1,2]
=> [1, 2]
[2] pry(main)> $ list.size

From: array.c (C Method):
Owner: Array
Visibility: public
Number of lines: 6

static VALUE
rb_ary_length(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    return LONG2NUM(len);
}
[3] pry(main)> $ list.length

From: array.c (C Method):
Owner: Array
Visibility: public
Number of lines: 6

static VALUE
rb_ary_length(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    return LONG2NUM(len);
}

Upvotes: 9

Uri Agassi
Uri Agassi

Reputation: 37409

Actually, there is a difference, but not in a simple Array. If you are using ActiveRecord's Association, there is a difference, as you can see here:

  • if you already load all entries, say User.all, then you should use length to avoid another db query

  • if you haven't anything loaded, use count to make a count query on your db

  • if you don't want to bother with these considerations, use size which will adapt

Upvotes: 3

Related Questions