1

I am a real Newb when it comes to Ruby, but I have been learning it using the code academy website. I started going outside the guidelines for the specific task I was supposed to be doing, only to my surprise I got an error when typing the following code:

print "please type in an integer for x:"
x = gets.to_i

print "please type in an integer for y:"
y = gets.to_i

if "x" < "y"
    puts "#{x} is less than #{y}"
elsif "x" > "y"
    puts "#{x} is greater than #{y}"
else
    puts "#{x} is equal to #{y}"
end

It is a really simple code but the end result is supposed to do this:

"x" < "y" will report "x is less than y"
"x" > "y" will report "x is greater than y"
"x" = "y" will report "x is equal to y"

both the smaller and greater work, but it cannot calculate if x and y are the same, instead just reporting "x is lees than y"

I'm not sure if it's a bug with the Code Academy website, or if it's something I'm doing wrong. Any help would be greatly appreciated.

Lewis H
  • 49
  • 11

1 Answers1

2

Write as below :

if x < y
    puts "#{x} is less than #{y}"
elsif x > y
    puts "#{x} is greater than #{y}"
else
    puts "#{x} is equal to #{y}"
end

"x" create a new string and not treated as the number you took from the console. But when you are write "#{x}", it is giving the number, but in string format using interpolation.

When you would write "x" > "y", you are checking/testing those string literals 'x' and 'y' by their lexicographical ordering, but x > y is the comparisons of the two numbers you took from the console using gets.to_i.

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Ahh, thank yo very much. I knew I was doing something as senile as forgetting the basic rules of Ruby. I applaud you, good sir. And I will also delete this question as it was a silly mistake. – Lewis H Mar 05 '14 at 17:45
  • alright sorry. I wish I was better at online forums like this one but unfortunately I don't take things like this as seriously as some other people. and yes I am talking about you. – Lewis H Mar 06 '14 at 22:45
  • @LewisHarris What do you mean by *yes I am talking about you* ? – Arup Rakshit Mar 06 '14 at 22:46