是否有可能比较Ruby中的私有属性?

时间:2009-12-02 03:07:31

标签: ruby attributes private instance-variables

我正在考虑:

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

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

但它不起作用。

错误消息是:

syntax error, unexpected tIVAR

如何比较同一类中的两个私有属性呢?

4 个答案:

答案 0 :(得分:11)

答案 1 :(得分:8)

有几种方法

吸气剂:

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

我不认为ruby有“朋友”或“受保护”访问的概念,甚至“私人”也很容易被攻击。使用getter创建一个只读属性,而instance_eval意味着你必须知道实例变量的名称,因此内涵是相似的。

答案 2 :(得分:4)

如果您不使用instance_eval选项(发布@jleedev),并选择使用getter方法,您仍然可以保留protected

如果你想在Ruby中使用protected方法,只需执行以下操作即可创建一个只能从同一类的对象中读取的getter:

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

答案 3 :(得分:0)

不确定,但这可能会有所帮助:

在课堂之外,这有点困难:

# 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