是否有可能私有属性在Ruby中比较? [英] Is it possible to compare private attributes in Ruby?

查看:190
本文介绍了是否有可能私有属性在Ruby中比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在:

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

我如何从同一类比较两个私有属性呢?

How can I compare two private attributes from the same class then?

推荐答案

有几种方法

消气:

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的意味着你必须知道实例变量的名字,所以内涵是相似的。

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.

这篇关于是否有可能私有属性在Ruby中比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆