Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over the first n elements of an array

Tags:

arrays

ruby

How can I iterate up to four objects of an array and not all? In the following code, it iterates over all objects. I need only the first four objects.

objects = Products.all(); arr=Array.new objects.each do |obj|     arr << obj end p arr 

Can it be done like objects=objects.slice(4), or is iteration the only way?

Edit:

I also need to print how many times the iteration happens, but my solution objects[0..3] (thanks to answers here) long.

i=0; arr=Array.new objects[0..3].each do |obj|     arr << obj     p i;     i++; end 
like image 477
Ben Avatar asked Mar 20 '12 02:03

Ben


2 Answers

You can get first n elements by using

arr = objects.first(n) 

http://ruby-doc.org/core-2.0.0/Array.html#method-i-first

like image 76
Kate Avatar answered Sep 28 '22 11:09

Kate


I guess the rubyst way would go by

arr=Array.new objects[0..3].each do |obj|     arr << obj end  p arr; 

so that with the [0..3] you create a subarray containing just first 4 elements from objects.

like image 45
Jack Avatar answered Sep 28 '22 11:09

Jack