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:

  1. @objects.limit(5)
  2. @objects.take(5)
  3. @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?

  1. limit not array method
  2. take requires argument; returns empty array if array empty.
  3. 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:

  1. limit(5) add scope of limit(5) activerecord::relation. it can not called on array, limit(5).limit(4) fail.

  2. first(5) add scope of limit(5) activerecord::relation. it can called on array .first(4).first(3) same .limit(4).first(3).

  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

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -