PDA

View Full Version : Newb program


P$HRAŁK
December 15th, 2007, 02:05 PM
I'm new to Ruby but its pretty much accurate to say I've fallen in love with it :rolleyes:

Anyway, I'm trying a very very simple user input program with the gets method. Problem is, I keep getting an error when in IRB which tells me that the line of code I've indicated with **********, can't be done because "String can't be coerced into fixnum". I've converted the year variable into an integer value and the same for the age variable, and I've converted the final product back into a string for the final "puts" output, so whats going wrong?

puts "What is your name?"
name = gets.chomp
puts "How old are you?"
age = gets.chomp
age.to_i
year = 2007
year =- age**********
year.to_s
puts name + " was born in " + year

bala
March 20th, 2008, 05:13 AM
puts "What is your name?"
name = gets.chomp
puts "How old are you?"
age = gets.chomp
age_int=age.to_i
year = Time.now.year
year -=age_int
year.to_s
puts name + " was born in " + year.to_s


u want explanation ??

csimons
April 21st, 2008, 04:47 PM
It seems that the issue is with your usage of the .to_i and .to_s methods.

Using (integer).to_s or (string).to_i will only return the value of the original value casted to the new type. It will not modify the original variable. So, for instance, the following program will result in an error:

x = 1
x.to_s
puts x + " is a cool number"

# will yield a "String can't be coerced into Fixnum
# (TypeError)" from the interpreter

However, the following will deliver the desired results:

x = 1
puts x.to_s + " is a cool number"

# will yield a "1 is a cool number"