Home > front end >  Code won't function properly without the Integer method for Ruby to properly identify whether m
Code won't function properly without the Integer method for Ruby to properly identify whether m

Time:12-31

I am brand new to programming. I am going through the Learn Ruby course on Codecademy. It's taking me through a exercise on experimenting with else/if statements. I'm attempting to run code where you input two integers (n and y) and print a statement based on whether n > y, n < y, or n == y.

As an example, when I input n = 5 and y = 15, it would print out the statement "I'm getting printed because n is greater than y) despite that not being true. Some set of numbers would print the correct statement, some set of numbers (as the one above) always printed the incorrect statement. After about 30 minutes of trying to figure out why it wouldn't work, I attempted adding the Integer method to my code and it works as intended. I'm just trying to understand why it wouldn't work properly prior to that.

Here is my code before:

print "Enter an integer for x:"
n = gets.chomp

print "Enter an integer for y:"
y = gets.chomp

if n < y
  print "I'm getting printed because #{n} is less than #{y}"
elsif n > y
  print "I'm getting printed because #{n} is greater than #{y}"
else
  print "I'm getting printed because #{n} is equal to #{y}"
end

Here is my code after adding the Integer method:

print "Enter an integer for n:"
n = Integer(gets.chomp)

print "Enter an integer for y:"
y = Integer(gets.chomp)

if n < y
  print "I'm getting printed because #{n} is less than #{y}"
elsif n > y
  print "I'm getting printed because #{n} is greater than #{y}"
else
  print "I'm getting printed because #{n} is equal to #{y}"
end

After going back in the lessons, I noticed an example Codecademy provided where they use the Integer method, but they do not go into detail about it. Regardless, I still added it to my code in the same fashion they used it in their example, and now it works properly. Like I said above, I just want to understand why it wouldn't work before and where it was going wrong in my code before I go any further in my lessons.

CodePudding user response:

gets returns the string entered by the user, including the newline character created by pressing enter. gets.chomp removes the newline character at the end of the string, but still leaves the input a string.

And strings are sorted and compared alphabetically. "aa" < "b" correct when comparing strings and in the same sense "11" < "2" is correct for strings containing numbers.

But Integer(gets.chomp) translates the user input from a string containing a number into an integer (an actual number). And therefore the comparison works as expected afterward.

Documentation of the methods in play:

  • Related