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)