How to make instance variables private in Ruby?

后端 未结 6 1232
孤城傲影
孤城傲影 2020-12-04 17:52

Is there any way to make instance variables \"private\"(C++ or Java definition) in ruby? In other words I want following code to result in an error.

class B         


        
6条回答
  •  遥遥无期
    2020-12-04 18:50

    I know this is old, but I ran into a case where I didn't as much want to prevent access to @x, I did want to exclude it from any methods that use reflection for serialization. Specifically I use YAML::dump often for debug purposes, and in my case @x was of class Class, which YAML::dump refuses to dump.

    In this case I had considered several options

    1. Addressing this just for yaml by redefining "to_yaml_properties"

      def to_yaml_properties
        super-["@x"]
      end
      

      but this would have worked just for yaml and if other dumpers (to_xml ?) would not be happy

    2. Addressing for all reflection users by redefining "instance_variables"

      def instance_variables
        super-["@x"]
      end
      
    3. Also, I found this in one of my searches, but have not tested it as the above seem simpler for my needs

    So while these may not be exactly what the OP said he needed, if others find this posting while looking for the variable to be excluded from listing, rather than access - then these options may be of value.

提交回复
热议问题