Ruby no implicit conversion of Fixnum into String (TypeError)
Asked Answered
K

2

22

I am trying to answer the following question from Chris Pine's "Learn to Program" book:

Leap years. Write a program that asks for a starting year and an ending year and then puts all the leap years between them (and including them, if they are also leap years). Leap years are years divisible by 4 (like 1984 and 2004). However, years divisible by 100 are not leap years (such as 1800 and 1900) unless they are also divisible by 400 (such as 1600 and 2000, which were in fact leap years). What a mess!

I get the following error when I run my code:

leap_year.rb:12:in +': no implicit conversion of Fixnum into String (TypeError) from leap_year.rb:12:in'

Here is my code:

#leap years

puts 'What is the starting year?'
starting_year = gets.chomp
puts 'What is the ending year?'
ending_year = gets.chomp

while starting_year <= ending_year
  if starting_year%4 == 0 && (starting_year%100 != 0 && starting_year%400 == 0)
    puts starting_year 
  end 
  starting_year+=1
end
Koester answered 3/12, 2013 at 16:34 Comment(1)
You can use gets.to_i to get an integer directly. The .to_i will ignore anything that doesn't "look" like a number, for instance "dog\n".to_i will give you a 0, rather than error out. This simulates typing 'dog' and then pressing enter when you are presented with that gets statement.Gadhelic
C
31

Add a .to_i to your gets.chomp calls. You're trying to do math operations on text. When inputted from the console, everything starts out as text, even if it's numeric looking text.

Cloverleaf answered 3/12, 2013 at 16:38 Comment(1)
thank you! I didn't know that inputted data from the console was automatically string data. Makes sense now.Koester
J
6

This is because the input from gets.chomp is a String. You cannot perform modulo (%) on a String. You need to convert it to an integer first.

Try this...

puts 'What is the starting year?'
starting_year = gets.chomp.to_i
puts 'What is the ending year?'
ending_year = gets.chomp.to_i

while starting_year <= ending_year
  if starting_year%4 == 0 && (starting_year%100 != 0 && starting_year%400 == 0)
    puts starting_year 
  end 
  starting_year+=1
end

Does that work now?

Jereme answered 3/12, 2013 at 16:38 Comment(1)
It definitely gets rid of the fixnum issue! the code still doesn't run all the way through though, but i'm still figuring out why.Koester

© 2022 - 2024 — McMap. All rights reserved.