74

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
sawa
  • 165,429
  • 45
  • 277
  • 381
Ben
  • 25,389
  • 34
  • 109
  • 165
  • 2
    Are you just trying to grab the first four objects, or are you trying to iterate over the first four objects? You can use the `take` method to grab the first n objects if you just wanted to iterate over them: `objects.take(4).each do...` – Marc Talbot Mar 20 '12 at 02:59
  • 1
    Why not `arr = Products.limit(4).to_a` (but you probably don't even need the `to_a`)? Any time you find yourself saying `Model.all` you should think again (and then a third time). – mu is too short Mar 20 '12 at 03:00
  • 1
    @Yosef you want [each_with_index](http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_with_index) ... also, `++` isn't a ruby operator – Kyle Mar 20 '12 at 03:19

5 Answers5

130

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

rainkinz
  • 10,082
  • 5
  • 45
  • 73
Kate
  • 1,326
  • 2
  • 8
  • 2
60

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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • 1
    Why iterate when just `arr = objects[0..3]` does the same thing? – mu is too short Mar 20 '12 at 03:03
  • this is the ruby way, but I observed it was much slower when compared to iterating over integer index (0 to 3) and fetching element via it (objects[i[). possibly because of copy work – Varun Garg Apr 03 '21 at 11:42
20

Enumerable#take returns first n elements from an Enumerable.

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
  • How does this differ from `#first`? Can `#first` only be used on an `Array` while `#take` can be used on _any_ `Enumerable`? – Joshua Pinter Aug 11 '18 at 23:46
6
arr = objects[0..3]

Thats all. You dont need the rest

Automatico
  • 12,420
  • 9
  • 82
  • 110
2

You can splice the array like this objects[0,4]

objects[0,4] is saying: start at index 0 and give me 4 elements of the array.

arr = objects[0,4].inject([]) do |array, obj|
  array << obj
end

p arr
Kyle
  • 21,978
  • 2
  • 60
  • 61