Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Inspect, to_s, p and puts in ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 572
    Comment on it

    In rails, sometimes we don't notice it but there is difference when you use puts to print an object and when you use just p to print an object. One thing let me clear for you, p is not a short form of puts, they both are different. Lets take an example:

    class Car
      def initialize(name)
        @name = name
      end
    end
    
    
    car = Car.new("swift")
    => #<Car:0x00000001ecb390 @name="swift">
    
    puts car
    => #<Car:0x00000001ecb390>
    
    p car
    => #<Car:0x00000001ecb390 @name="swift">

     

    In the above example you can see the difference, this difference is because of the reason that p prints the result by applying inspect method to the object while puts prints the result by applying to_s method on the object.

    Thus in case of to_s (or puts) method as you can see in the example also, it only takes the class name along with a number displayed with a hex, but in case of inspect (or p), it also returns the instance variables apart from the class name and the hex.

    Both the puts and p are generally used for debugging the code, so if you want to modify the result of the puts for an object based on your requirement you can do that by overriding the to_s method.

    class Car
      def initialize(name)
        @name = name
      end
    
      def to_s
        "This is an object of class: Car\n Name is #{@name}"
      end
    end
    
    ## Now if you run
    > car = Car.new("swift")
    > puts car
    
    ## It will give output like this:
    
    This is an object of class Car
     Name is swift
     => nil

     

 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: