What's wrong with my elsif statement? Please Help!


#1

Shouldn’t the outcomes be the opposite? I don’t get it, please help me!


#2

gets returns a string with a newline character. Neither input can be cast to a number, so the strings are compared. 1 comes before 4.


#3

Thank you! Is there a way I can make it compare input numbers?


#4

Remove the newline character from the inputs using .chomp

gets.chomp

then if they can be cast to numbers the comparison will work. If they remain as strings, then 1 still comes before 4. You may have to cast to numbers manually rather than rely upon coercion.

x = gets.chomp
x = x.to_i

Consider the following…

puts "Enter x"
x = gets.chomp          # 10
puts "Enter y"
y = gets.chomp          # 4

puts x > y              # false  => indicates no coercion (conversion to number)

puts x.to_i > y.to_i    # true

#5

Thank you so much for your help!


#6

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