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,
First of all, use of the term "recursion" is not correct here. Recursion
occurs when a function calls itself. The code above is iterative, not
recursive.
For example (this can be written more tersely but I am trying to
illustrate something clearly):
def factorial(n)
return 1 if n <= 1 # Termination condition
return n * factorial(n - 1) # Recursive call
end
factorial(6) => 720
The same thing iteratively is
def factorial(n)
fact = 1
n.downto(1) { |i| fact *= i }
fact
end
Second of all, your code uses strings where it should use integers.
Writing
while number_of_bottles != '0'
is doing a string comparison. '0' is a 1-character string consisting of
the character '0'. You really want an integer.
So, rewriting your code to be more Rubyish,
def repeat(type)
number_of_bottles = 99
while number_of_bottles != 0
puts "#{number_of_bottles} bottles: If one falls,
#{number_of_bottles - 1} bottles."
puts "#{type}#{number_of_bottles - 1}:"
number_of_bottles = gets.chomp.to_i
end
end
Now, to ensure that someone types in what you want, you should create a
simple function to get what you are looking for, e.g.
def expect(msg, expected_value)
puts "#{msg}#{expected_value}:"
loop do
actual_value = gets.chomp.to_i
return actual_value if actual_value == expected_value
puts "Sorry, expected #{expected_value} but got #{actual_value}"
end
end
Note that this function is not perfect; it does not check to see if an
actual integer was entered, so if people enter non-digits they will be
seen as 0 values. I leave this as a exercise for the reader...
Anyway, we now change the original function to the following:
def repeat(msg)
number_of_bottles = 99
while number_of_bottles != 0 do
puts "#{number_of_bottles} bottles: If one falls,
#{number_of_bottles - 1} bottles."
number_of_bottles = expect(msg, number_of_bottles - 1)
end
end
Hope this helps. I recommend buying and reading Pragmatic Programming in
Ruby. It will answer a lot of your Ruby questions.
···
--
Posted via http://www.ruby-forum.com/\.