Skip to content

Commit 5f2a1b6

Browse files
Watson1978claude
andcommitted
Object#inspect: instance_variables_to_inspect フック (Ruby 4.0) を追記
Ruby 4.0 から、プライベートメソッド instance_variables_to_inspect を 定義することで、既定の inspect 出力に含めるインスタンス変数を制御できる ようになった (Feature #21219)。パスワードなどの機密情報を持つインスタンス 変数を inspect の出力から除外する用途に使える。 このフックは Kernel のプライベートメソッドで、既定の実装は nil を返す (その場合は全インスタンス変数が表示される)。表示したいインスタンス変数名の Symbol 配列を返すようにオーバーライドすると、その変数だけが表示される。 #@SInCE 4.0 で分岐し、inspect の項に説明と例を追記した。実機 4.0.6 で確認済み。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 65ff2c6 commit 5f2a1b6

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

manual/api/_builtin/Object.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -916,6 +916,27 @@ end
916916
p Bar.new.inspect # => "#<Bar:0x0300c868 @bar=1>"
917917
```
918918

919+
#@since 4.0
920+
inspect をオーバーライドしていない場合、
921+
instance_variables_to_inspect を定義することで、inspect の出力に含める
922+
インスタンス変数を制御できます。このメソッドは、表示したいインスタンス変数名を
923+
[c:Symbol] の配列で返すようにします(デフォルトの実装は nil を返し、その場合は
924+
全てのインスタンス変数が表示されます)。パスワードなどの機密情報を持つ
925+
インスタンス変数を inspect の出力(ログなど)に含めたくない場合に利用できます。
926+
927+
```ruby
928+
class Foo
929+
def initialize
930+
@a = 1
931+
@password = "secret"
932+
@b = 2
933+
end
934+
private def instance_variables_to_inspect = [:@a, :@b]
935+
end
936+
p Foo.new.inspect # => "#<Foo:0x0300c868 @a=1, @b=2>"
937+
```
938+
#@end
939+
919940
- **SEE** [m:Kernel?.p]
920941

921942
### def instance_variable_get(var) -> object | nil

0 commit comments

Comments
 (0)