ruby / irb

interactive Ruby
BSD 2-Clause "Simplified" License
392 stars 119 forks source link

IRB does not use `inspect` method to inspect subclass of `Struct` #1036

Closed natsu1375 closed 1 day ago

natsu1375 commented 2 days ago
$ irb --version
irb 1.14.1 (2024-09-25)

irb(main):001> Person=Struct.new do def inspect; "Person_inspect" end end; [Person.new, Person.new.inspect]
=> [#<struct Person>, "Person_inspect"]

irb(main):002> PersonX=Class.new do def inspect; "PersonX_inspect" end end; [PersonX.new, PersonX.new.inspect]
=> [PersonX_inspect, "PersonX_inspect"]

Expect Person.new should be evaluated as Person_inspect in IRB console, since we define a inspect method for it. But got #<struct Person>.

An instance of a plain class PersonX works as expected.

tompng commented 1 day ago

This is not an issue of IRB but a specification of PP.

p Person.new
#=> Person_inspect
pp Person.new
#=> #<struct Person>

Same for array

arr = [].tap{def _1.inspect = "(empty)"}
p arr
#=> (empty)
pp arr
#=> []

You need to define pretty_print and pretty_print_cycle to customize the output of pp.