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
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
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
Addressing for all reflection users by redefining "instance_variables"
def instance_variables
super-["@x"]
end
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.