mortee
11/6/2007 5:10:00 AM
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
Yes, you're doing it wrong (:
If you want to set a variable to 1, simply set it so:
Victory = 1
If you want to increment it each time some condition is met, then set it
to a bigger value:
Victory = Victory + 1
or more simply
Victory += 1
Also let me point out that you seem to completely swap the meaning of
assignment and testing. When you verify for equality, you use the ==
operator, and when assigning, you use =, not the other way around. So if
you want to check if you just read a specific string from the console,
you do this:
if inputcommand == "search"
otherwise inputcommand will be *set to* the value "search", and the
whole expression's value checked by "if", which will always evaluate to
true.
Note that values whose name starts with a capital letter are constants,
or class or module names (which also happen to be constants). While you
*can* in fact alter the value of a constant in Ruby, you shouldn't use
them as variables (e.g. you get a warning when you modify them, and also
you can't create them inside methods, AFAIK). So you should just use
variable names starting with lowercase letters or underscore.
Further, you can simply use boolean values when you use a variable as a
boolean flag, you don't have to compare integers.
victory = false
...
until victory
...
victory = true
end
Also, in such a simple loop you can avoid using a condition variable
altogether, and simply break out the loop when you want to:
while true
...
break # immediately finish the loop when passing this line
end
I guess most of what I've described can be found in any entry level
guides to Ruby. You really should take your time to read and understand
one - go look around www.ruby-lang.org for documentation.
mortee