Arrays in Ruby: Take vs Limit vs First -
suppose have array of objects in rails @objects
if want display first 5 objects, difference between using:
@objects.limit(5)
@objects.take(5)
@objects.first(5)
i talking front end (ruby), not sql. reason why objects not limited in sql because same array may used elsewhere without applying limit it.
does have object instantiation?
- limit not array method
- take requires argument; returns empty array if array empty.
- first can called without argument; returns nil if array empty , argument absent.
source 2.0 take
static value rb_ary_take(value obj, value n) { long len = num2long(n); if (len < 0) { rb_raise(rb_eargerror, "attempt take negative size"); } return rb_ary_subseq(obj, 0, len); }
source 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)
add scope oflimit(5)
activerecord::relation
. it can not called on array,limit(5).limit(4)
fail.first(5)
add scope oflimit(5)
activerecord::relation
. it can called on array.first(4).first(3)
same.limit(4).first(3)
.take(5)
run query in current scope, build objects , return first 5. it works on arrays,model.take(5)
not work, though other 2 work.
Comments
Post a Comment