Ruby - p() method to inspect objects

Introduction

Ruby p method can inspect objects and print their details, like this:

p( anobject ) 

where anobject can be any type of Ruby object.

For example, let's suppose you create the following three objects: a string, a number, and a Product object:

Demo

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

a = "hello" 
b = 123 
c = Product.new( "ring", "a gift" ) 

p( a ) 
p( b ) 
p( c )

Result

Related Topic