Question

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.

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top