Iterate over the first n elements of an array

RubyArrays

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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.

Solution 3 - Ruby

Enumerable#take returns first n elements from an Enumerable.

Solution 4 - Ruby

arr = objects[0..3]

Thats all. You dont need the rest

Solution 5 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenView Question on Stackoverflow
Solution 1 - RubyKateView Answer on Stackoverflow
Solution 2 - RubyJackView Answer on Stackoverflow
Solution 3 - RubyMladen JablanovićView Answer on Stackoverflow
Solution 4 - RubyAutomaticoView Answer on Stackoverflow
Solution 5 - RubyKyleView Answer on Stackoverflow