Jump to content

Help with if statements

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Mash

Mash

    Newbie

  • Members
  • Pip
  • 5 posts
So, I'm using a program called 'Hackety Hack!' which is a beginner tutorial that uses the Ruby program designed to help people grasp the basics of programming, and more specifically, Ruby.

Now, I'm doing the tutorials, and it tells me to write these lines of code;

secret_number = 42

guess = ask " Guess the number!"

if guess == secret_number

 alert "Correct!"

else

 alert "Incorrect!"

end

Now, on the line that says 'if guess == secret_number', if I have the double equal signs as shown, then every single input turns up as incorrect. However, if I have only one equal sign, then every input turns up as correct.

Now, this is the exact code I was told to put in by the tutorial, so I don't exactly know what's wrong with it... but the compiler just doesn't want to use it.

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
I apologise if you had already discovered this.

Generally some languages separate characters from integers, so 23 is a number and not the characters 2 and 3 separately together.

If I recall, ruby has a "to string" method to apply to a variable:

if guess.to_s == secret_number.to_s

This should force strings to be compared.

Alexander.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,254 posts
  • Location:C:\Countries\US
Or the "to integer" or "to float" methods could work too.
if guess.to_i == secret_number.to_i then alert ...
or
if guess.to_f == secret_number.to_f then alert ...

(5.to_s should also work, because in Ruby, everything is an object.)


By the way, how did you get the alert () method to work? I mean, I tried it and it threw an error at me.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users