Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • puts vs p in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 435
    Comment on it

    While writing the code, we often need to print a particular object and see the result. In rails we use puts and p for that.
    Both will display the result but there is a difference between them.puts prints the result by applying to_s on an object where as p prints the result by inspecting the object.

     

    For example we have a class Product
    
    class Product
      def inspect
        "Inside method inspect"
      end
    end


     
    Now we will create an object of Product class

    puts Product.new
    puts Product.new.to_s
    p Product.new

     

    Output will be:

    #<Product:0x00000003461510>
    #<Product:0x000000034614c0>
    Inside method inspect
     


     Here puts will simply print the class object , but p does inspecting of the object, will give a string as output as the method name is inspected itself.
    Another difference by example:

    class Product
      def initialize(product_name, quantity)
        @product_name = product_name
        @quantity = quantity
      end
    end
     
    product = Product.new("Car",1)
     
    puts product
    puts product.inspect
    p product

     

    Output will be:

    #<Product:0x0000000320bc98>
    #<Product:0x0000000320bc98 @product_name="Car", @quantity=1>
    #<Product:0x0000000320bc98 @product_name="Car", @quantity=1>

    As you can see, puts prints the class name of the object along with the position of the object in memory. Whereas p on the other hand prints the class name and all the instance variables of the object. So if you put an object,  you need to add .inspect to the object.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: