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


#1

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"
else
    puts "x is equal to y"
end


#2

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


#3

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


#4

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

"123"

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

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.


#5

Thank you for your answer! :slight_smile:


#6

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.

Ronald


#7

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


#8

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