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

前端 未结 2 1022
醉梦人生
醉梦人生 2021-01-19 17:04

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 somethi

相关标签:
2条回答
  • 2021-01-19 17:39

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

    @bar.instance_variable_get(:@wah)
    
    0 讨论(0)
  • 2021-01-19 17:40

    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 讨论(0)
提交回复
热议问题