pp icon indicating copy to clipboard operation
pp copied to clipboard

Pretty Prettying a SimpleDelegator object which implements `#inspect` doesn't work

Open marcoroth opened this issue 9 months ago • 1 comments

Hey there!

I come across this weird bug(?) when I was trying to inspect an object in irb. Since irb uses pp to print the objects I'm opening this issue here.

In my case I have a class that inherits from SimpleDelegator:

require "delegate"

class Parent
  def inspect
    "<parent>"
  end
end

class Child < SimpleDelegator
  def inspect
    "<child>"
  end
end

In irb I noticed it because the objects are being shown using inspect:

irb(main):001> Parent.new.inspect
# => "<parent>"

irb(main):002> Parent.new
# => <parent>

irb(main):003> Child.new(Parent.new).inspect
# => "<child>"

irb(main):004> Child.new(Parent.new)
# => <parent>

Personally, I would have expected the last one to also show <child>. Now after digging into this a bit more (thanks @st0012), it seems like you can also reproduce this in pp directly using:

require "delegate"
require "pp"

class Parent
  def inspect
    "<parent>"
  end
end

class Child < SimpleDelegator
  def inspect
    "<child>"
  end
end

parent = Parent.new
child = Child.new(parent)

pp child 
#=> "<parent>"

marcoroth avatar Mar 07 '25 21:03 marcoroth

I don't think it is preferable to call Child#inspect over the delegated pretty_print, as calling inspect is an indirect fallback. A possible mitigation would be to respect pretty_print (or pretty_print_cycle) if defined. That means, #60 will work as follows:

class Child < SimpleDelegator
  def inspect
    "<child>"
  end

  def pretty_print(q)
    q.text inspect
  end
end
pp child
#=> "<parent>"

nobu avatar Oct 05 '25 08:10 nobu