Is it possible to compare private attributes in Ruby?

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

    There are several methods

    Getter:

    class X
      attr_reader :a
      def m( other )
        a == other.a
      end
    end
    

    instance_eval:

    class X
      def m( other )
        @a == other.instance_eval { @a }
      end
    end
    

    instance_variable_get:

    class X
      def m( other )
        @a == other.instance_variable_get :@a
      end
    end
    

    I don't think ruby has a concept of "friend" or "protected" access, and even "private" is easily hacked around. Using a getter creates a read-only property, and instance_eval means you have to know the name of the instance variable, so the connotation is similar.

提交回复
热议问题