SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Sep 2007
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Need Help with a Very Simple Program

    I've been working my way through 'Learning to Program,' by Chris Pine, to begin to understand both Ruby and the general concepts of programming. Anyway, the little program I've written accomplishes a simple task: it asks for your favorite number, adds one to it, then returns it to you. Here it is:

    Code:
    Code Ruby:
    puts 'Hey there, I\'m Uno.'
    puts 'What\'s your favorite number?'
    number = gets.chomp
    better = number.to_i + 1
    puts better + '...That\'s better.'
    For some reason, I get an error (in terminal) that says :'String can't be coerced into Fixnum (TypeError).' Why can't this variable--which contains a numeric string--be converted into an integer?

  2. #2
    SitePoint Zealot daveporter's Avatar
    Join Date
    Mar 2002
    Location
    Perth, Western Australia
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Maxiscool,

    Are you sure you are getting that error with the 'better = ...' line you have shown ?

    I think you are getting that error with .to_s + 1 rather than to_i + 1
    ( which of course is an invalid statement ! )

    HTH - Dave Porter

  3. #3
    SitePoint Zealot daveporter's Avatar
    Join Date
    Mar 2002
    Location
    Perth, Western Australia
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    puts "That's better: #{better}"

    might work better for the last line !

    cheers Dave

  4. #4
    SitePoint Enthusiast
    Join Date
    Mar 2001
    Location
    Hailsham, UK
    Posts
    62
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    The error is on the last line.

    better is an integer on line 4 (not a numeric string), and you are trying to add a string to it in line 5. (This happens before puts is called.)

    You need to convert better to a string to concatenate the rest of the string with it.

    puts better.to_s + '...That\'s better.'

    Good luck,
    Ian


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •