I am learning Ruby as my first programming language using the excellent
tutorial by Chris P. Learn to Program, by Chris Pine
Everything was going well until I tried to write a simple program to
print out the 99 bottles of beer on the wall song. Here is my code.
int = 99
while int != 1
puts int.to_s + ’ bottles of beer on the wall, ’ + int.to_s + ’
bottles of beer’
int.to_i - 1
puts 'Take one down, pass it around, ‘+int.to_s + ’ bottles of beer on
the wall’
end
When I run this, I get into a loop of 99. It never subtracts one. I have
figured out all the other programs that you are to try, but for some
reason the problem in this is escaping me. Any help will be greatly
appreciated.
Thanks.
On Wed, Apr 04, 2012 at 08:26:23PM +0900, Bryan Bales wrote:
int.to_i - 1
puts 'Take one down, pass it around, ‘+int.to_s + ’ bottles of beer on
the wall’
end
When I run this, I get into a loop of 99. It never subtracts one. I have
figured out all the other programs that you are to try, but for some
reason the problem in this is escaping me. Any help will be greatly
appreciated.
You’re not actually storing the result of subtracting 1 from int
anywhere,
so as far as Ruby is concerned, it never changes.
You want something like
int = int - 1
instead of
int.to_i - 1
Note that calling to_i on int is not really necessary here, since int
already contains an integer.
Dan
On 04/04/2012 02:26 PM, Bryan Bales wrote:
int.to_i - 1
like for me int.to_i - 1 does operation but do not handle result
try:
int = int -1
Instead of i = i - 1, you can also write i -= 1. This is the short form
(there’s also a short form for some other operators like +, *, / etc.)
Bryan, and if you have your loop working you can do
$ ri19 Fixnum#downto
and see how it can be done without an explicit loop. 
Btw, for the printing I find it more convenient to do
puts #{int} bottles of beer on the wall, #{int} bottles of beer’
than
puts int.to_s + ’ bottles of beer on the wall, ’ + int.to_s + ’
bottles of beer’
Kind regards
robert
you must assign the result of int.to_i - 1 to int. And you don’t need
the .to_i
So: int = int -1 (or int -= 1) should do what you want.