# Returns a pretty printed object as a string.
# In order to use this method you must first require the PP module:
# See the PP module for more information.
# prints arguments in pretty form.
# pp returns argument(s).
objs.size <= 1 ? objs.first : objs
module_function :pp # :nodoc:
# A pretty-printer for Ruby objects.
# All examples assume you have loaded the PP class with:
# Standard output by #p returns this:
# #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
# Pretty-printed output returns this:
# @genspace=#<Proc:0x81feda0>,
# #<PrettyPrint::GroupQueue:0x81fed3c
# [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# @output=#<IO:0x8114ee4>,
# pp(obj1, obj2, ...) #=> [obj1, obj2, ...]
# Output <tt>obj(s)</tt> to <tt>$></tt> in pretty printed format.
# It returns <tt>obj(s)</tt>.
# == Output Customization
# To define a customized pretty printing function for your classes,
# redefine method <code>#pretty_print(pp)</code> in the class.
# <code>#pretty_print</code> takes the +pp+ argument, which is an instance of the PP class.
# The method uses #text, #breakable, #nest, #group and #pp to print the
# To pretty-print JSON refer to JSON#pretty_generate.
# Tanaka Akira <akr@fsij.org>
# Outputs +obj+ to +out+ in pretty printed format of
# +width+ columns in width.
# If +out+ is omitted, <code>$></code> is assumed.
# If +width+ is omitted, 79 is assumed.
def PP.pp(obj, out=$>, width=79)
q.guard_inspect_key {q.pp obj}
# Outputs +obj+ to +out+ like PP.pp but with no indent and
# PP.singleline_pp returns +out+.
def PP.singleline_pp(obj, out=$>)
q.guard_inspect_key {q.pp obj}
def PP.mcall(obj, mod, meth, *args, &block)
mod.instance_method(meth).bind(obj).call(*args, &block)
@sharing_detection = false
# Returns the sharing detection flag as a boolean value.
# It is false by default.
attr_accessor :sharing_detection
# and preserves the previous set of objects being printed.
if Thread.current[:__recursive_key__] == nil
Thread.current[:__recursive_key__] = {}.taint
if Thread.current[:__recursive_key__][:inspect] == nil
Thread.current[:__recursive_key__][:inspect] = {}.taint
save = Thread.current[:__recursive_key__][:inspect]
Thread.current[:__recursive_key__][:inspect] = {}.taint
Thread.current[:__recursive_key__][:inspect] = save
# Check whether the object_id +id+ is in the current buffer of objects
# to be pretty printed. Used to break cycles in chains of objects to be
def check_inspect_key(id)
Thread.current[:__recursive_key__] &&
Thread.current[:__recursive_key__][:inspect] &&
Thread.current[:__recursive_key__][:inspect].include?(id)
# Adds the object_id +id+ to the set of objects being pretty printed, so
# as to not repeat objects.
Thread.current[:__recursive_key__][:inspect][id] = true
# Removes an object from the set of objects being pretty printed.
Thread.current[:__recursive_key__][:inspect].delete id
# Adds +obj+ to the pretty printing buffer
# using Object#pretty_print or Object#pretty_print_cycle.
# Object#pretty_print_cycle is used when +obj+ is already
# printed, a.k.a the object reference chain has a cycle.
group {obj.pretty_print_cycle self}
group {obj.pretty_print self}
pop_inspect_key(id) unless PP.sharing_detection
# A convenience method which is same as follows:
# group(1, '#<' + obj.class.name, '>') { ... }
def object_group(obj, &block) # :yield:
group(1, '#<' + obj.class.name, '>', &block)
# A convenience method, like object_group, but also reformats the Object's
def object_address_group(obj, &block)
str = Kernel.instance_method(:to_s).bind(obj).call
group(1, str, '>', &block)
# A convenience method which is same as follows:
# The list is separated by comma with breakable space, by default.
# #seplist iterates the +list+ using +iter_method+.
# It yields each object to the block given for #seplist.
# The procedure +separator_proc+ is called between each yields.
# If the iteration is zero times, +separator_proc+ is not called at all.
# If +separator_proc+ is nil or not given,
# +lambda { comma_breakable }+ is used.
# If +iter_method+ is not given, :each is used.
# For example, following 3 code fragments has similar effect.
# q.seplist([1,2,3]) {|v| xxx v }
# q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
def seplist(list, sep=nil, iter_method=:each) # :yield: element
sep ||= lambda { comma_breakable }
list.__send__(iter_method) {|*v|
# A present standard failsafe for pretty printing any given Object
object_address_group(obj) {
seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
v = v.to_s if Symbol === v
# A pretty print for a Hash
seplist(obj, nil, :each_pair) {|k, v|
class SingleLine < PrettyPrint::SingleLine # :nodoc:
module ObjectMixin # :nodoc:
# 1. specific pretty_print
# 3. generic pretty_print
# A default pretty printing method for general objects.
# It calls #pretty_print_instance_variables to list instance variables.
# If +self+ has a customized (redefined) #inspect method,
# the result of self.inspect is used but it obviously has no
# This module provides predefined #pretty_print methods for some of
# the most commonly used built-in classes for convenience.
method_method = Object.instance_method(:method).bind(self)
inspect_method = method_method.call(:inspect)
if inspect_method && /\(Kernel\)#/ !~ inspect_method.inspect
elsif !inspect_method && self.respond_to?(:inspect)
# A default pretty printing method for general objects that are
# detected as part of a cycle.
def pretty_print_cycle(q)
q.object_address_group(self) {
# Returns a sorted array of instance variable names.
# This method should return an array of names of instance variables as symbols or strings as:
def pretty_print_instance_variables
# Is #inspect implementation using #pretty_print.
# If you implement #pretty_print, it can be used as follows.
# alias inspect pretty_print_inspect
# However, doing this requires that every class that #inspect is called on
# implement #pretty_print, or a RuntimeError will be raised.
if /\(PP::ObjectMixin\)#/ =~ Object.instance_method(:method).bind(self).call(:pretty_print).inspect
raise "pretty_print is not overridden for #{self.class}"
PP.singleline_pp(self, '')
def pretty_print(q) # :nodoc:
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '[]' : '[...]')
def pretty_print(q) # :nodoc:
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '{}' : '{...}')
def pretty_print(q) # :nodoc:
def pretty_print(q) # :nodoc:
q.group(1, sprintf("#<struct %s", PP.mcall(self, Kernel, :class).name), '>') {
q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
def pretty_print_cycle(q) # :nodoc:
q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
def pretty_print(q) # :nodoc:
q.text(self.exclude_end? ? '...' : '..')
class File < IO # :nodoc:
def pretty_print(q) # :nodoc:
q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
q.text "ino="; q.pp self.ino; q.comma_breakable
q.text sprintf("mode=0%o", m)
q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
(m & 0400 == 0 ? ?- : ?r),
(m & 0200 == 0 ? ?- : ?w),
(m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
(m & 04000 == 0 ? ?x : ?s)),
(m & 0040 == 0 ? ?- : ?r),
(m & 0020 == 0 ? ?- : ?w),
(m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
(m & 02000 == 0 ? ?x : ?s)),
(m & 0004 == 0 ? ?- : ?r),
(m & 0002 == 0 ? ?- : ?w),
(m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
(m & 01000 == 0 ? ?x : ?t)))
q.text "nlink="; q.pp self.nlink; q.comma_breakable
q.text "uid="; q.pp self.uid
pw = Etc.getpwuid(self.uid)
q.breakable; q.text "(#{pw.name})"
q.text "gid="; q.pp self.gid
gr = Etc.getgrgid(self.gid)
q.breakable; q.text "(#{gr.name})"
q.text sprintf("rdev=0x%x", self.rdev)
if self.rdev_major && self.rdev_minor
q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
q.text "size="; q.pp self.size; q.comma_breakable
q.text "blksize="; q.pp self.blksize; q.comma_breakable
q.text "blocks="; q.pp self.blocks; q.comma_breakable
q.breakable; q.text "(#{t.tv_sec})"
q.breakable; q.text "(#{t.tv_sec})"
q.breakable; q.text "(#{t.tv_sec})"