Introduction

To see how you can use to_s with a variety of objects and test how a Product object would be converted to a string in the absence of an overridden to_s method.

Demo

class Product 
    def initialize( aName, aDescription ) 
      @name         = aName # w w w  .j  av a  2  s  . com
      @description  = aDescription 
    end 
                           
    def to_s # override default to_s method 
         "The #{@name} Product is #{@description}\n" 
    end 
end 
puts(Class.to_s)        #=> Class 
puts(Object.to_s)       #=> Object 
puts(String.to_s)       #=> String 
puts(100.to_s)          #=> 100 
puts(Product.to_s)     #=> Product 

t = Product.new( "Sword", "a weapon" ) 
puts(t.to_s)  
puts(t.inspect)

Result

classes such as Class, Object, String, and Product simply return their names when the to_s method is called.

An object, such as the Product object t, returns its identifier-which is the same identifier returned by the inspect method:

Related Topic