How do I indicate that an integer is negative in Ruby?


How do I indicate that an integer is negative?
When I executed the following code and gave x=-1 and y=-2, the result was wrong. It printed "x is less than y." Why is that?

Thank you!

print "Give x. x="
x = gets.chomp
print"Give y. y="
y = gets.chomp
if x<y
    print "x is less than y"
elsif x>y
    print "y is less than x"
    puts "x is equal to y"


You're not using any integers in your code
The string "-1" is lexicographically smaller than "-2"


How do I indicate that x and y are integers in the code? Thank you!


They're not, so you can't indicate that they are, doesn't make sense.
However, you can read strings and create integers from what you read. Google "ruby string to int" (this is what you'd do whenever you want to know how to do some action)
The way that's done is by reading digits from left to right, multiplying the current value by 10 and adding the next one each time


0 * 10 + 1
1 * 10 + 2
12 * 10 + 3

However, code for that already exists as part of the language, and by googling you can find out where it is and how to use it.


Thank you for your answer! :slight_smile:


There is nothing in your code, which would operate on integers. The
method gets returns a String, chomp also returns a String, so x and y
are strings. With x<y, you do a lexicographic comparision on strings.

The String class has a method called to_i, which returns the integer
which is represented by the string.



I changed the code to x = gets.chomp.to_i and y = gets.chomp.to_i and it worked.
Thank you :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.