On Fri, May 16, 2008 at 1:38 PM, Jason Lillywhite
<jason.lillywhite / gmail.com> wrote:
> I found some issues with the above proposed solutions that I wanted to
> ask about:
>>>
>>> class NameIt
>>>  def initialize(name)
>>>    @name = name
>>>  end
>>>  def to_s
>>>    puts "My name is: #{@name}"
>>>  end
>>
>>   def to_s
>>     "My name is: " << name
>>     # no puts
>>   end
>>
>>> end
>
> Clarifications/comments:
>
> it appears that << name needs to be changed to << @name for it to work.
> I assume this is because the scope of "name" is only known in the
> initialize method and not the to_s method? I understand the scope of the
> instance variable to be visible throughout the class. Is this the
> reason?

Yep.  You are correct.  Sorry 'bout that.

> Another question:
>
> I entered this in:
> class NameIt
>  def initialize(name)
>    @name = name
>  end
>  def to_s
>    puts "My name is: " << @name
>  end

Leave out the puts in #to_s.  You want #to_s to return a string, not
execute a console output.

> end
> names = %w( tom sally doug john)
> nameits = names.map {|name| NameIt.new(name)}
> nameits.each{|n| puts n.to_s}

#puts calls #to_s, so you doing...

puts n.to_s

...is redundant.  Just do...

puts n

hth,
Todd