views:

25

answers:

3

Hello,

I have the following:

@books.each do |book|
... stuff
end

I'm curious to learn. How can I update the above to do something like loop through @books but not more than 6 times, MAX/ceiling of 6?

Thanks

+1  A: 
@books.each_with_index do |book, i|
  if i >= 6
    break
  end
  ... stuff
end
shoebox639
Spinning through what could be a very large list is inefficient. The `break` technique described in Jacob Relkin's answer is a better approach.
tadman
heh, caught me before I changed it.
shoebox639
+1  A: 
@books.each_with_index do |book, i|
   break if i > 5
   #stuff...
end
Jacob Relkin
I see you fixed your arguments, but you've got the classic "Off By One" error. `i` goes from 0..5, not 0..6 if you want only 6 elements.
tadman
+3  A: 

The easiest way to do this is to take a slice of the Array and iterate over that:

@books[0,6].each do |book|
  # ...
end

The alternative is to keep the Array intact and bail out of the loop when you're done:

@books.each_with_index do |book, i|
  break if (i == 6)

  # ...
end
tadman
+1 for elegance.
shoebox639
@tadman, what if books doesn't have 6 items? for the first exapmle? trying to understand what that's doing?
TheExit
That's a simple Array slice and will take a maximum of 6 items. If the array is only of size 3 then you will get only 3. The first parameter is the index of where to start, which in your case is 0, but you can adjust this to take the 7th through 12th using `[6,6]`
tadman
When in doubt, toy around in `irb`! `%w[ a b c d e f g h ][0,3]` yields `[ 'a', 'b', 'c' ]`
tadman