From: Jeff Patterson Date: 2008-03-24T23:34:48+09:00 Subject: Re: Beginner's question 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. When doing a loop of this type, concentrate on what is static and what needs to change at each iteration. In each verse the only thing that changes are the numbers so: while bottles > 0 after_this_loop = bottles-1 puts "#{bottles} of beer on the wall. #{bottles} of beer. Take one down and pass it around #{bottles=bottles-1} bottles of beer on the wall" bottles = bottles -1 end A ruby programmer would probably do something like: 99.downto(1) do |bottles| puts "#{bottles} of beer on the wall. #{bottles} of beer. Take one down and pass it around #{bottles=bottles-1} bottles of beer on the wall" end Now, figure out how to make the verse come out right when bottles = 1 -- Posted via http://www.ruby-forum.com/.