From 9cea466c95a3d9b1b553e434ee1f46235db2120b Mon Sep 17 00:00:00 2001 From: Jason Frey Date: Wed, 13 Aug 2025 13:37:34 -0400 Subject: [PATCH] Support new instance_variables_to_inspect method from Ruby core This supports the new `instance_variables_to_inspect` method from Ruby core that was added in ruby/ruby#13555. If `instance_variables_to_inspect` is defined, then `pretty_print_instance_variables` will use it. Additionally, this commit introduces tests for both `pretty_print_instance_variables` and `instance_variables_to_inspect`. --- lib/pp.rb | 3 ++- test/test_pp.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/pp.rb b/lib/pp.rb index 5318395..eb9f80d 100644 --- a/lib/pp.rb +++ b/lib/pp.rb @@ -399,7 +399,8 @@ def pretty_print_cycle(q) # This method should return an array of names of instance variables as symbols or strings as: # +[:@a, :@b]+. def pretty_print_instance_variables - instance_variables.sort + ivars = respond_to?(:instance_variables_to_inspect) ? instance_variables_to_inspect : instance_variables + ivars.sort end # Is #inspect implementation using #pretty_print. diff --git a/test/test_pp.rb b/test/test_pp.rb index c71445c..e721260 100644 --- a/test/test_pp.rb +++ b/test/test_pp.rb @@ -130,6 +130,20 @@ def a.to_s() "aaa" end assert_equal("#{a.inspect}\n", result) end + def test_iv_hiding + a = Object.new + def a.pretty_print_instance_variables() [:@b] end + a.instance_eval { @a = "aaa"; @b = "bbb" } + assert_match(/\A#\n\z/, PP.pp(a, ''.dup)) + end + + def test_iv_hiding_via_ruby + a = Object.new + def a.instance_variables_to_inspect() [:@b] end + a.instance_eval { @a = "aaa"; @b = "bbb" } + assert_match(/\A#\n\z/, PP.pp(a, ''.dup)) + end + def test_basic_object a = BasicObject.new assert_match(/\A#\n\z/, PP.pp(a, ''.dup))