加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:54:11 所属栏目:百科 来源:网络整理
导读:我在考虑: class X def new() @a = 1 end def m( other ) @a == other.@a endendx = X.new()y = X.new()x.m( y ) 但它不起作用. 错误消息是: syntax error,unexpected tIVAR 我如何比较来自同一类的两个私有属性呢? 解决方法 有几种方法 消气: class X a
我在考虑:

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

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

解决方法

有几种方法

消气:

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意味着您必须知道实例变量的名称,因此内涵类似.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读