Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

8. Objects and Classes > 8.10. Getting a Human-Readable Printout of Any Object

8.10. Getting a Human-Readable Printout of Any Object

Problem

You want to look at a natural-looking rendition of a given object.

Solution

Use Object#inspect. Nearly all the time, this method will give you something more readable than simply printing out the object or converting it into a string.

	a = [1,2,3]
	puts a
	# 1
	# 2
	# 3

	puts a.to_s
	# 123

	puts a.inspect
	# [1, 2, 3]
	puts /foo/
	# (?-mix:foo)
	puts /foo/.inspect
	# /foo/
	f = File.open('foo', 'a')
	puts f
	# #<File:0xb7c31c30>
	puts f.inspect
	# #<File:foo>

Discussion

Even very complex data structures can be inspected and come out looking just like they would in Ruby code to define that data structure. In some cases, you can even run the output of inspect through eval to recreate the object.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint