From: Arlen Christian Mart Cuss Date: 2007-11-06T14:18:59+09:00 Subject: Re: Affecting variables inside a while loop that are initialised outside its scope Hi, On Tue, 2007-11-06 at 13:05 +0900, Rawn wrote: > How can I do it? Sorry if this is stupid or something but I'm just > learning to program (starting with ruby) and this seemed like a more > interesting way to start than endless arithmatic operations.. > > #!/usr/bin/ruby > Inventory = Array.new > Discovered = Array.new > Victory = 0 > puts "You are in a dim room. You can just make out a door by the light > shining through the cracks." > while Victory < 1 > inputcommand = gets.chomp! > if inputcommand = "search" > Victory + 1 == Victory > end > end > > > I'd like to change the value of Victory to 1 when "search" is typed > into the prompt, thus causing the while loop to end, ending the > script. This may be the completly wrong way to go about doing this but > atleast tell me how to do what I want before you school me in the > proper way of doing things ; ) > thanks in advance Firstly, something to become used to is that in Ruby, anything beginning with a capital letter is a constant! Watch: irb(main):001:0> Victory = 1 => 1 irb(main):002:0> Victory = 2 (irb):2: warning: already initialized constant Victory => 2 irb(main):003:0> This basically means you should leave capital letters at the start of names for values which don't change -- for example, there's this constant: irb(main):003:0> RUBY_VERSION => "1.8.6" irb(main):004:0> That's built-in to Ruby, and of course it's not changing, so it's rightfully a constant. So, your variable may need to be called 'victory' instead. Secondly, to assign a new value to 'victory', just do it like this: irb(main):002:0> victory = 0 => 0 irb(main):003:0> victory = victory + 1 => 1 irb(main):004:0> victory = victory + 1 => 2 irb(main):005:0> Notice the way `victory' is evaluated on the right-hand side first, then it's all assigned to `victory' on the left. There's even a shorthand for adding to a variable: irb(main):005:0> victory += 1 => 3 irb(main):006:0> victory += 1 => 4 irb(main):007:0> You'll learn a lot more about this as you advance in your Ruby. Finally, I'll let you know that "==" is for testing equality, whereas "=" is always for assigning: irb(main):010:0> victory == 3 => false irb(main):011:0> victory == 4 => true irb(main):012:0> victory == 5 => false irb(main):013:0> So, == doesn't change the variable - it just returns 'true' or 'false' like some other comparison operators do: irb(main):013:0> victory < 5 => true irb(main):014:0> victory <= 2 => false irb(main):015:0> These are what you use with 'if' or 'while' and similar constructs. (this is why you need to take care when writing them not to forget an extra '=' sign!) Good luck! Arlen