Josh Hollis Josh Hollis - 1 year ago 104
Ruby Question

String can't be coerced into Fixnum Ruby

I'm trying to learn ruby, and was tasked with creating a simple program that grabs user input, and then uses an elsif statement to give a possible 3 different answers. Here's my code:

print "What is your birth year?"
year = gets.chomp
age = 2016 - year
if age >= 40
puts "You're old!"
elsif age.between?(25, 39)
puts "You aren't too old!"
puts "You're just a baby!"

However, I keep getting "String can't be coerced into Fixnum"

I don't recall in the lessons doing something like I'm doing for the "age" variable, so I could be doing it wrong, but I also couldn't find an answer in my lessons or online. Any help would be greatly appreciated!

Answer Source

Remember that gets returns a string value, and in Ruby strings and numeric values are completely different things. Some other languages will coerce them as necessary, like PHP, Perl or JavaScript, but Ruby does not.

To make this work:

year = gets.chomp.to_i

Although technically to_i alone is usually sufficient.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download