76

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 
3
  • 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... Commented Mar 20, 2012 at 2: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). Commented Mar 20, 2012 at 3:00
  • 1
    @Yosef you want each_with_index ... also, ++ isn't a ruby operator Commented Mar 20, 2012 at 3:19

5 Answers 5

138

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

Sign up to request clarification or add additional context in comments.

1 Comment

"Hey Ruby, you're slick AF."
61

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.

2 Comments

Why iterate when just arr = objects[0..3] does the same thing?
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
20

Enumerable#take returns first n elements from an Enumerable.

1 Comment

How does this differ from #first? Can #first only be used on an Array while #take can be used on any Enumerable?
6
arr = objects[0..3] 

Thats all. You dont need the rest

Comments

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 

2 Comments

Why inject when just arr = objects[0,4] will do?
I assumed the OP wanted to iterate over an array and do something other than just collect the elements.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.