user39980
user39980

Reputation:

Guess A Number - Ruby Online

I have been trying to create a Ruby program that will be running online where a user can guess a number, and it will say higher or lower. I know it will take a random number store in a variable, then run a loop? With conditionals to check?

Im not asking for full code, the basic structure for I can use this to get me going.

Any idea how i would do this? I found info to create a random number like this:

x = rand(20)

UPDATE: My code I am going to be working with is something like this: http://pastie.org/461976

Upvotes: 0

Views: 1268

Answers (1)

Chris Bunch
Chris Bunch

Reputation: 89873

I would say to do something like this:

x = rand(20)

loop {
  # get the number from the user somehow, store it in num
  if num == x
    # they got it right
    break
  elsif num > x
    # the guess was too high
  else
    # the guess was too low
  end
}

If you're running it online, this structure may not be feasible. You may need to store the guess in the user's session and have a textbox for the guess, and submit it to a controller which would have the above code without the loop construct, and just redirect them to the same page with a message if they didn't get it right.

Upvotes: 3

Related Questions