开发者

In Ruby, foo.inspect can print out all instance variables -- can we print out an individual one if there is no accessor?

开发者 https://www.devze.com 2023-02-18 05:34 出处:网络
Often, we can use p foo or foo.inspect to see the instance variables, but is it only the default behavior and the object can choose to show something else开发者_如何学Go (or hide all instance variable

Often, we can use p foo or foo.inspect to see the instance variables, but is it only the default behavior and the object can choose to show something else开发者_如何学Go (or hide all instance variables) (probably by re-defining the inspect method).

The main question is, if I can see for foo.inspect that there is @bar being an object, having instance variable @wah, that has a value of "hello", can I print out @wah directly, if there is no accessor (reader) available for @bar and @wah? Usually, it should not be readable if there is no accessor, but what if for debugging purpose?


In Ruby, all access protection can be circumvented using reflection:

@bar.instance_variable_get(:@wah)


Trying to print a variable defined by attr_writer from outside the class will throw an error (undefined method 'wah' for #<Bar:0x0000...>) - but for debugging purposes you can use instance_variable_get as such:

b = Bar.new(:wah => "Hello")
b.wah # undefined method

b.instance_variable_get("@wah") # => "Hello"
0

精彩评论

暂无评论...
验证码 换一张
取 消