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

前端 未结 2 1024
醉梦人生
醉梦人生 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:40

    Trying to print a variable defined by attr_writer from outside the class will throw an error (undefined method 'wah' for #) - 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"
    

提交回复
热议问题