How to make instance variables private in Ruby?

后端 未结 6 1242
孤城傲影
孤城傲影 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:36

    Unlike methods having different levels of visibility, Ruby instance variables are always private (from outside of objects). However, inside objects instance variables are always accessible, either from parent, child class, or included modules.

    Since there probably is no way to alter how Ruby access @x, I don't think you could have any control over it. Writing @x would just directly pick that instance variable, and since Ruby doesn't provide visibility control over variables, live with it I guess.

    As @marcgg says, if you don't want derived classes to touch your instance variables, don't use it at all or find a clever way to hide it from seeing by derived classes.

提交回复
热议问题