David Masover
4/27/2009 9:58:00 PM
On Sunday 26 April 2009 15:01:37 Mike West wrote:
> Of course after I post, I figure out the solution!
>
> puts 'Hello, what is your favorite number?'
> number = gets.chomp
> better = number.to_i+1
> puts number.to_s + '?? Aren\'t you aware that ' + better.to_s + ' is a
> far better choice?'
>
>
> Is that the best way to accomplish this? You can't mix strings and
> integers- at all? Period?
As others have said, the best way is most likely string interpolation. I'd do
it like this:
number = gets.chomp.to_i
puts "#{number}?? Aren't you aware that #{number+1} is a far better choice?"
The double-quotes allow interpolation. The following is roughly equivalent,
but will likely execute slower:
number = gets.chomp.to_i
puts number.to_s + '?? Aren\'t you aware that ' + (number+1).to_s + ' is a far
better choice?'
Or, another way:
print number
print '?? Aren\'t you aware that '
print number + 1
puts ' is a far better choice?'
You absolutely can mix them, you just have to explicitly convert them, or use
them in a context where this is done for you. For instance, 'print' and 'puts'
will call to_s on whatever you pass them. 'p' will call inspect on whatever
you pass it.