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
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
@books.each_with_index do |book, i|
if i >= 6
break
end
... stuff
end
@books.each_with_index do |book, i|
break if i > 5
#stuff...
end
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