#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    1
    Rep Power
    0

    Adding Variables


    Hello, I am just starting out with Ruby and I am reading a book and at the end of a chapter it gives me a little project but doesn't ask me what I did or tell me why it didn't work. So here it is...

    I am trying to write a program that asks for a persons favorite car company and model and then at the end add up the letters and tell them how many there are. Not the characters but letters. Here is what I have got...

    puts 'What\'s your favorite car company?'
    name = gets.chomp
    puts '' +name+ '\'s a great car company.'
    puts 'What\'s your favorite model?'
    name1 = gets.chomp
    puts 'That\'s cool, ' +name1+ ' is a nice model.'
    puts 'Did you know that ' +name+ ' ' +name1+ '
    puts ' has ' +name.length.to_s + name1.length.to_s+ '
    puts ' letters in it?'

    So my issue is that it is adding the strings instead of the integers, I think. How do I make it add the integers to give me the full letter count of both names?

    Thank you very much for any help. I am new at this.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2009
    Posts
    76
    Rep Power
    115
    This is my first attempt to help someone with Ruby, and I barely know what Ruby is. Please excuse me if I am wrong, but I will take this opportunity to learn at least what Ruby code looks like.
    If someone here feels like telling me "Don't answer if you don't know what you're doing", then please give the right answer instead.
    However, it does look like you are converting name.length to a string with to_s(). You need to sum the integers instead. I don't know how (yet) but I would just guess something like this:
    Code:
    (name.length + name1.length).to_s()
    I will have look around and let you know what I find. You can do that as well.

    Edit:
    Can you do it like this?
    Code:
    puts " has #{name.length + name1.length}"
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2009
    Posts
    16
    Rep Power
    0
    I would use
    Code:
    puts 'Did you know that '+name+' '+name1
    puts 'has '+(name.length+name1.length).to_s+' letters in it'
    The problem is that you have tried to add the string name.length to the string name1.length which is similar to trying to add 'fred' and 'bert'.

IMN logo majestic logo threadwatch logo seochat tools logo