From: Stefano Crocco Date: 2008-03-24T23:42:50+09:00 Subject: Re: Beginner's question On Monday 24 March 2008, Peter Johnsson wrote: > This question may be a bit too "simple" for this forum which seems to > target intermediate and advanced users, but if that's the case someone > could perhaps direct me to a place which is better for asking this > question? > > I have just recently decided to try and learn programming (namely > Ruby), and in order to do so I've been using a tutorial called "learn to > program" (http://pine.fm/LearnToProgram/). > Everything has gone just fine until I reached the 6:th chapter (Flow > Control) in which the author teaches about among other things branching > and loop-methods. > I think I understand most of it, however, I'm having very large > difficulties with the " A Few Things to Try" part of the chapter. > I find the "99 beer bottles"-program utterly impossible to do. I > realise that I should somehow use the methods listed on the page, but I > just can seem to know how. My initial idea is to create a variable > called "bottles" which at first is 99 and then subtract 1 in every new > verse until the variable hits 0, where I was thinking I could use the > "while"-method to end the program. Each new value would be inserted into > the lyrics. It would look something like this I suppose (please don't > laugh, I know it doesn't really do anything at all). > > bottles = 99 > > while bottles != 0 > # Need help here. > end > > I stumbled upon a site which showed how one scould program this in Ruby > (http://99-bottles-of-beer.net/language-ruby-1272.html), but the problem > is it doesn't use the same methods. It's more advanced since it creates > classes and defines methods, something which I think lies a bit too far > ahead for me, and I somehow want to learn things in "the right order". > > I'm thankful for any tips as well as code-examples. Thank you very much. Inside the while loop, you need to do essentially three things: a) display the verse related to the current number of bottles b) break a bottle (that is, decrease the variable bottle by one) c) display the verse related to the new number of bottles Each of these goals may be translated in a line of code: while bottles !=0 puts bottles.to_s + "bottles of beer on the wall, " + bottles.to_s + "bottles of beer." bottles -= 1 puts "Take one down and pass it around, "+ bottles.to_s + "bottles of beer on the wall." end This works almost perfectly, except for the fact that it doesn't treat the case of one bottle and of 0 bottle in a special way (when there's only one bottle, it should print 1 bottle, when there are no more bottles, it should write so). To correct this, you should insert some if statements inside the while loop. I hope this helps Stefano