At the bottom is the exercise to have Ruby print the lyrics for 99 bottles of beer but with using an iterator. I can make the program print fine with a loop, but i just do not understand the concept of iterators. Or maybe i’m trying too hard and missing something simple but here is what i have:
beer = ["99"]
beer[0].to_i.times do |bottles|
puts bottles + " bottles of beer on the wall."
beer[0] -= 1
end
I’ve tried for an hour playing with different classes and “iterators” but i’m not sure what part of this isn’t working out. I guess it might help if i knew which part of code was the actual iterator itself! And the error parser doesn’t make much sense either to me.
This makes sense. I knew it was making it harder than necessary, i just assumed i had to do this with an array and that is where i kept getting hung up.
One of the core aspects of Ruby and one of the reasons why some people like it so much is that there is usually about 300 different ways of doing the same thing. It’s perfectly possible to use arrays, especially if you need to use the list later. Here’s another way to do it, in one line, using an array and iterators:
beer = Array.new(100).fill{|i|99-i}.each{|i|puts "%d bottles of beer on the wall." % i}
Since in this example, the array holds consecutive values, you can also write it using a range instead. Like friedo says, unfortunately, Ruby doesn’t really let you make reverse-ordered ranges like 99…0, so it’s not as neat as it should be.
bottles = (0..99).each{|i|puts "%d bottles of beer on the wall." % (99-i)}