How To Print Object In Ruby

In this blog post, we will discuss various methods to print objects in Ruby, which can be helpful when debugging or understanding the code. We will discuss four primary methods:

  • puts
  • p
  • print
  • pp (Pretty Print)

Using puts to Print Objects in Ruby

puts is a standard Ruby method used to print the value of an object followed by a newline character. It calls the to_s method to convert the object into a string representation, which is then printed to the console.

student = {name: “John”, age: 25, city: “San Francisco”}

puts student

Output:

    {:name=>"John", :age=>25, :city=>"San Francisco"}
    

Using p to Print Objects in Ruby

p is another method in Ruby that is used for printing the value of an object. It calls the inspect method on the object, which returns a more detailed string representation of the object, and then prints the string followed by a newline character.

student = {name: “John”, age: 25, city: “San Francisco”}

p student


Output:

    {:name=>"John", :age=>25, :city=>"San Francisco"}
    

Using print to Print Objects in Ruby

print is another method in Ruby used for printing objects. The difference between print and puts is that print does not append a newline character at the end. It also calls the to_s method to convert the object into a string representation.

student = {name: “John”, age: 25, city: “San Francisco”}

print student

Output:

    {:name=>"John", :age=>25, :city=>"San Francisco"}
    

Using pp (Pretty Print) to Print Objects in Ruby

pp stands for Pretty Print, and it is part of the Ruby standard library. It provides a more readable output for complex objects such as nested arrays and hashes. To use pp, you must first require the ‘pp’ library.

require ‘pp’

student = {name: “John”, age: 25, city: “San Francisco”, courses: [“Math”, “Science”, “History”]}

pp student

Output:

    {:name=>"John",
     :age=>25,
     :city=>"San Francisco",
     :courses=>["Math", "Science", "History"]}
    

Conclusion

In this blog post, we have seen various methods to print objects in Ruby, including puts, p, print, and pp (Pretty Print). Depending on your need, you can choose the method that suits best for printing objects in Ruby. Remember that puts and print use the to_s method, while p uses the inspect method. On the other hand, pp is ideal for printing complex, nested objects in a more readable format.