Is it possible to compare private attributes in Ruby?

后端 未结 4 753
无人共我
无人共我 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

    If you don't use the instance_eval option (as @jleedev posted), and choose to use a getter method, you can still keep it protected

    If you want a protected method in Ruby, just do the following to create a getter that can only be read from objects of the same class:

    class X
        def new()
            @a = 1
        end
        def m( other ) 
            @a == other.a
        end
    
        protected
        def a 
          @a
        end
    end
    
    x = X.new()
    y = X.new()
    x.m( y ) # Returns true
    x.a      # Throws error
    

提交回复
热议问题