From: "Jesús Gabriel y Galán" Date: 2010-09-29T16:06:22+09:00 Subject: Re: Error - "`+': can't convert nil into String" On Wed, Sep 29, 2010 at 5:03 AM, Paul Roche wrote: > > Why does the code below give me this error? What can I do to fix it? > > /people3.rb:4:in `+': can't convert nil into String (TypeError) > om C:/Ruby192/people3.rb:4:in `to_s' > > class Person > attr_accessor :fname, :lname, :age > def to_s > "hi " + @fname + ", " + @lname > end > > end @fname is nil, and you are trying to call the + method on it. Hence the error. The recommended way would be something like: class Person attr_accessor :fname, :lname, :age def to_s "hi #{@fname}, #{@lname}" end end irb(main):001:0> class Person irb(main):002:1> attr_accessor :fname, :lname, :age irb(main):003:1> def to_s irb(main):004:2> "hi #{@fname}, #{@lname}" irb(main):005:2> end irb(main):006:1> irb(main):007:1* end => nil irb(main):008:0> Person.new.to_s => "hi , " irb(main):009:0> p = Person.new => hi , irb(main):010:0> p.lname = "Smith" => "Smith" irb(main):011:0> p.to_s => "hi , Smith" irb(main):012:0> p.fname = "John" => "John" irb(main):013:0> p.to_s => "hi John, Smith" Jesus.