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.
Asked
Active
Viewed 194 times
3

Arturo Herrero
- 12,772
- 11
- 42
- 73

Vass
- 2,682
- 13
- 41
- 60
-
1Can you clarify as to which class you are referring to? e.g. ruby's Array, ActiveRecord's Association or any object? – punkle Dec 18 '14 at 14:34
-
@punkle, my interest is in multidimensional arrays of integers where if I index an excessively large number of dimensions I get an error thrown as expected, but with size a fixnum comes back. I had put it as an answer but deleted it gathered a lot of negative feedback – Vass Dec 18 '14 at 14:57
2 Answers
9
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);
}

Arturo Herrero
- 12,772
- 11
- 42
- 73
3
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 uselength
to avoid another db queryif you haven't anything loaded, use
count
to make a count query on your dbif you don't want to bother with these considerations, use
size
which will adapt

Community
- 1
- 1

Uri Agassi
- 36,848
- 14
- 76
- 93