Ruby - Class Inspecting Objects

Introduction

Consider the following code.

Demo

class Product 
      def initialize( aName, aDescription ) 
          @name           = aName # from  w  ww .  jav a  2s  . co  m
          @description  = aDescription 
      end 
                           
      def to_s # override default to_s method 
       "The #{@name} Product is #{@description}\n" 
      end 
end 

t1 = Product.new("Sword", "a real thing") 
t2 = Product.new("Ring", "a gift") 
puts t1.to_s 
puts t2.to_s 
# The inspect method lets you look inside an object 
puts "Inspecting 1st Product: #{t1.inspect}" 
puts "Inspecting 2nd Product: #{t2.inspect}"

Result

The inspect method is defined for all Ruby objects.

It returns a string containing a human-readable representation of the object.

The returned message begins with the class name, Product.

This is followed by a number, Ruby's internal identification code for this particular object.

Next the names and values of the object's variables are shown.

Related Topic