In Ruby, foo.inspect can print all instance variables - is it possible to print a separate one if there is no access?

Often we can use p foo or foo.inspect to view instance variables, but this is only the default behavior, and the object can choose to show something else (or hide all instance variables) (possibly by overriding the inspect method).

The main question: if I see foo.inspect that there is an @bar object that has an @bar instance variable that has the value "hello" , can I print @wah directly if there is no (reader) access for @bar and @wah ? Generally, it should not be readable if it does not have access, but what if for the purpose of debugging?

+4
source share
2 answers

In Ruby, all access protection can be bypassed with reflection:

 @bar.instance_variable_get(:@wah) 
+6
source

Attempting to print the variable defined by attr_writer 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" 
+1
source

Source: https://habr.com/ru/post/1344797/


All Articles