On Mon, Mar 8, 2010 at 5:11 PM, Mike Peltzer <mspeltzer / gmail.com> wrote:

> puts 'what\'s your favorite number?'
> var1 =3D 1
> num =3D gets.chomp
> puts 'well ' + num.to_i + ' + var1 is better'
>
> when I run it, this is the error i get:
> ---------------------------------------
> what's your favorite number?
> 3
> ri20min.rb:5:in `+': can't convert Fixnum into String (TypeError)
> =A0from ri20min.rb:5:in `<main>'

'well ' is an object that is an instance of the String class.

It has a method, +, that takes an argument which will be combined with
the value of the String object, returning a new instance of String. It
expects the argument to respond to #to_str.

num points to an object that is an instance of String.

When you call the #to_i method on it, you get back an object that is
an instance of Fixnum. Fixnum doesn't normally respond to #to_str, so
when it is passed as the argument to String#+, an exception is thrown.

Now, try this:

-----
class Fixnum
  def to_str
    self.to_s
  end
end

puts 'what\'s your favorite number?'
var1 =3D 1
num =3D gets.chomp
puts 'well ' + num.to_i + ' + var1 is better'
-----

> ruby /tmp/a.rb
what's your favorite number?
4
well 4 + var1 is better

That's not probably what you actually intend, but you can see that it
works, now.

If you actually want to add num and var, you probably want something like t=
his:

puts 'well ' + (num.to_i + var1) + ' is better'

But you probably shouldn't do what I showed you in an actual program.
One of the powerful things about Ruby is that you can change core
classes if you need to, but you really should have a good reason, and
this isn't one. Better to just do this:

puts 'well ' + (num.to_i + var1).to_s + ' is better'

And, for that matter, this is even better:

puts "well #{num.to_i + var1} is better"

You see, variable interpolation in an instance of String calls to_s
for you on the result.

Hope that helps,


Kirk Haines