Tuesday, May 3, 2011

Guess A Number - Ruby Online

Hey,

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)

Thanks,

Ryan

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

From stackoverflow
  • 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.

    Coughlin : Any suggestions to the online part. That is what I mainly confused on. Let me whip up some code that i have so far with that.
    Coughlin : Check out the pastie link I posted in my original question. That should give yo an idea.
    Bob Aman : Yeah, the "online" part is just remembering the original number from the session.
    Coughlin : Any idea with the code I have to get an example. I am clueless for htat part
    Coughlin : Something like this: http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI/Session.html

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.