Suppose you have an array of objects in Rails @objects
If I want to display the first 5 objects, what is the difference between using:
@objects.limit(5)
@objects.take(5)
@objects.first(5)
I am talking about the front end (Ruby), NOT SQL. The reason why the objects are not limited in SQL is because the same array may be used elsewhere without applying a limit to it.
Does it have anything to do with object instantiation?
Source for 2.0 take
static VALUE
rb_ary_take(VALUE obj, VALUE n)
{
long len = NUM2LONG(n);
if (len < 0) {
rb_raise(rb_eArgError, "attempt to take negative size");
}
return rb_ary_subseq(obj, 0, len);
}
Source for 2.0 first:
static VALUE
rb_ary_first(int argc, VALUE *argv, VALUE ary)
{
if (argc == 0) {
if (RARRAY_LEN(ary) == 0) return Qnil;
return RARRAY_PTR(ary)[0];
}
else {
return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
}
}
In terms of Rails:
limit(5)
will add the scope of limit(5)
to an ActiveRecord::Relation
. It can not be called on an array, so limit(5).limit(4)
will fail.
first(5)
will add the scope of limit(5)
to an ActiveRecord::Relation
. It can also be called on an array so .first(4).first(3)
will be the same as .limit(4).first(3)
.
take(5)
will run the query in the current scope, build all the objects and return the first 5. It only works on arrays, so Model.take(5)
will not work, though the other two will work.