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

查看:35
本文介绍了是否可以比较 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天全站免登陆