Josh Hollis
Josh Hollis

Reputation: 35

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!"
 else
    puts "You're just a baby!"
end

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!

Upvotes: 1

Views: 167

Answers (1)

tadman
tadman

Reputation: 211560

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.

Upvotes: 1

Related Questions