“99 Bottles of Beer” in a Loop
Two weeks ago, I never thought I’d be introduced to a new framework that actually makes working with Ruby a little easier. Then I met Rails. Imagine having to set up your own resources before a big presentation. This may entail setting up a projector, connecting it to your computer, making sure the microphones are in working order, etc. Doesn’t seem too bad if you’re used to doing it for so long, right? Then one day, you’re up for another presentation and you discover the room is already configured for you. Your only task is making your presentation to your audience. “Wait…I don’t have to set up my resources any more? All I have to do is present my information to the audience? Sweet!” That’s what Rails does for programmers.
In class, we were given a bonus exercise to add a page in our app that contains the lyrics for “99 Bottles of Beer on the Wall.” I considered many ways to display the lyrics. Do I put all of the lyrics in an array? How can I display all of the lyrics to this song? Ninety-nine bottles is a lot of beer and a lot of lyrics! A couple of things that stand out about these lyrics is that it’s repetitive, the only thing that will change is the number. A loop should do the trick:
I defined a method called “bottles_method” and created an instance variable called “@lyrics” which is set to an empty array. This is where I plan to store all of my lyrics. Then I used a method called “downto” which will iterate through all of the numbers starting with the number (99) “down to” the last number (0). Then I created my loop: for each “number,” if the “number” is greater than zero, shovel the lyrics into the “@lyrics” array. I’m converting the “number” to a string in order to concatenate it with the song lyrics which are also strings. The “else” statement says: if the number is not greater than 0, then shovel the string, “No more bottles??” into the “@lyrics” array, then render the page.
In the “bottles.html.erb” file, I embedded some Ruby code to add a loop. This will separate the song lyrics to its own line. Before adding the loop, all of the lyrics were displayed right next to each other in one continuous line which made it more difficult to read. Adding a loop to the html.erb file to separate the lines is visually better. Check it out:
Once the loop reaches zero, it will output the string I have listed in the “else” statement at the very bottom:
Pretty cool! In this bonus challenge, I learned about the “downto” method which I looked up and decided it would work well in my code. I thought I’d only be using one loop, but the second loop used to separate each line was very helpful in formatting the lyrics on the page.