Is there no difference between "size" and "length" in Ruby?
In the documentation for size
we can read here that 'size () is an alias for length'. For length
( doc ) "Returns the number of items in itself. May be zero." and this length is "Also alias as: size". The functionality may be very similar, but I'm wondering if other implementations contain any other functionality besides returning the number of elements in an array or collection. The length and size of the words seem to imply a difference, especially since size would make me think about memory size in bytes rather than number of elements.
source to share
This is exactly the same implementation.
You can see in the Ruby 2.3.1 source code , which is an alias:
rb_define_alias(rb_cArray, "size", "length");
Also, if you check pry and pry-doc , you can see that it is 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);
}
source to share
Actually, there is a difference, but not simple Array
. If you are using ActiveRecord
Association
, there is a difference as you can see here :
if you have already loaded all records, say
User.all
then you should uselength
to avoid another db requestIf you haven't downloaded anything, use
count
to make a count query on your dbif you don't want to bother with these considerations, use
size
which will adapt
source to share