Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Applying limit and offset to array

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.92k
    Comment on it

    In rails we can apply limit and offset to arrays in different ways.


    1> Using "slice" method.

    slice takes 2 arguments, the first one being the "starting_index" & the second one is the "number_of_elements".

    syntax :-
    arrayobj.slice(offset,limit)

    Ex :--

      a = [4,7,1,8,23,65,3,74,90,51,56,79,28,83,68] 
      res = a.slice(4,7) {where 4 is the offset and 5 is the limit} 
      => [23, 65, 3, 74, 90, 51, 56]
    

    2> we can directly use the "starting_index" & "length" on the array object

    syntax :-
    arrayobj[start,length] {here start will be treated as offset & length will be treated as limit}

    Ex:-

       a = [4,7,1,8,23,65,3,74,90,51,56,79,28,83,68]
       res = a[5,2]
       => [65, 3]
    

    3> Limit & offset can also be applied using the methods "drop" & "first" on array objects.

    Ex :- If we want to give offset as 8 and limit as 3, we can use it as :-

      a = [4,7,1,8,23,65,3,74,90,51,56,79,28,83,68]
      a = a.drop(8)
      => [90, 51, 56, 79, 28, 83, 68]
      a = a.first(3)
      => [90, 51, 56]
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: