From: dblack@... Date: 2006-11-27T22:47:00+09:00 Subject: Re: simple loops and recursion Hi -- On Mon, 27 Nov 2006, ishamid wrote: > Hi, > > I'm a total newbie, and this is my very first message. I'm going > through Chris Pine's Learn to Program; almost half done. > > Problem: Consider the following working code: > > =============== > def repeat type > number_of_bottles = '99' > while number_of_bottles != '0' > puts number_of_bottles.to_s + ' bottles:' + ' If one falls, ' + > (number_of_bottles.to_i - 1).to_s + ' bottles.' > type + (number_of_bottles.to_i - 1).to_s + ':' > number_of_bottles = gets.chomp > end > end > > repeat 'Type ' > =============== > > I want to add a recursion conditional: If there are 98 bottles left, > one should type '98'; if there are 97, one should type '97' etc. At 0 > bottles the programs ends. What I want is an additional conditional > recursion, so that e.g. if, at 98 bottles, I type anything other than > '98', the program recursively tells me to type '98' until I type '98'. > > Every way I've tried this gives me a " undefined local variable or > method `number_of_bottles' " type of error, or else the program keeps > going back to 99. Here's a rewrite that might give you some ideas. def repeat(prompt) bottles = 99 until bottles.zero? expected = bottles-1 puts "#{bottles} bottles: If one falls, #{expected} bottles." print "#{prompt} #{expected}: " input = gets.chomp until input == expected.to_s print "Wrong! Try again: " input = gets.chomp end bottles = input.to_i end end repeat("Type") David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org