Topic: Noob Program Question

Hey guys, I'm new to Ruby and picked up Chris Pine's book as suggested by you guys.  Great book.  Need some help. Can some one explain why this program I wrote won't work.  It's a suggestion from his book to try.  I think I'm messing up with the idea of adding integers and strings. 

puts 'Hello, do you want to play a game?  What\'s your first name?'
first = gets.chomp
puts ''
puts 'Your name is ' + first + '?  Well that\'s an interesting name.'
puts ''
puts 'Pleased to meet you ' + first + '.'
puts ''
puts 'Please, next tell me your favorite number:'
number = gets.chomp
puts ''
puts 'That\'s not a bad number.'
puts ''
puts 'I would have chose ' + number.to_i + 1 + '.'

Thanks, any info would be great.

Isaiah

Last edited by IsaiahSonjeow (2009-04-05 13:37:05)

Re: Noob Program Question

I'm relatively new to the language as well, but would recommend looking into ruby string interpolation, I love it and it's much cleaner.  My code would be similar, just a few notable changes.

puts "Hello, do you want to play a game?  What's your first name?"
first = gets.chomp
puts ''
puts "Your name is #{first}?  Well that's an interesting name."
puts ''
puts "Pleased to meet you #{first}."
puts ''
puts "Please, next tell me your favorite number:"
number = gets.to_i
puts ''
puts "That's not a bad number."
puts ''
puts "I would have chosen #{number + 1}."

I used double quotes as that allows the interpolation to be carried out and not just showing the text as it appears.  I removed the second chomp, as the to_i will do that for us, and I also did it when you assigned the variable.  Your code fixed is below:

puts 'Hello, do you want to play a game?  What\'s your first name?'
first = gets.chomp
puts ''
puts 'Your name is ' + first + '?  Well that\'s an interesting name.'
puts ''
puts 'Pleased to meet you ' + first + '.'
puts ''
puts 'Please, next tell me your favorite number:'
number = gets.chomp
puts ''
puts 'That\'s not a bad number.'
puts ''
puts 'I would have chosen ' + (number.to_i + 1).to_s + '.'

I think the issue is that you were using the string(+) operator to join a number and a string, which isn't what it's for.