Is it possible to compare private attributes in Ruby?

后端 未结 4 840
无人共我
无人共我 2021-01-14 02:09

I\'m thinking in:

class X
    def new()
        @a = 1
    end
    def m( other ) 
         @a == other.@a
    end
end

x = X.new()
y = X.new()
x.m( y ) 
         


        
4条回答
  •  半阙折子戏
    2021-01-14 02:30

    Not sure, but this might help:

    Outside of the class, it's a little bit harder:

    # Doesn't work:
    irb -> a.@foo
    SyntaxError: compile error
    (irb):9: syntax error, unexpected tIVAR
            from (irb):9
    
    # But you can access it this way:
    irb -> a.instance_variable_get(:@foo)
        => []
    

    http://whynotwiki.com/Ruby_/_Variables_and_constants#Variable_scope.2Faccessibility

提交回复
热议问题