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
takemethod to grab the first n objects if you just wanted to iterate over them:objects.take(4).each do...arr = Products.limit(4).to_a(but you probably don't even need theto_a)? Any time you find yourself sayingModel.allyou should think again (and then a third time).++isn't a ruby operator