Ruby 在不需要公开私有字段的情况下创建equals方法

Ruby 在不需要公开私有字段的情况下创建equals方法,ruby,access-specifier,Ruby,Access Specifier,我正在编写一个Ruby类,希望重写==方法。我想说的是: class ReminderTimingInfo attr_reader :times, :frequencies #don't want these to exist def initialize(times, frequencies) @times, @frequencies = times, frequencies end ... def ==(other) @times

我正在编写一个Ruby类,希望重写==方法。我想说的是:

class ReminderTimingInfo
   attr_reader :times, :frequencies #don't want these to exist

   def initialize(times, frequencies)
      @times, @frequencies = times, frequencies
   end

   ...

   def ==(other)
      @times == other.times and @frequencies == other.frequencies
   end
end
我如何在不公开时间和频率的情况下做到这一点

后续行动:

class ReminderTimingInfo

  def initialize(times, frequencies)
    @date_times, @frequencies = times, frequencies
  end

  ...

  def ==(other)
    @date_times == other.times and @frequencies == other.frequencies
  end

  protected

  attr_reader :date_times, :frequencies
end

如果将times和frequencies访问器设置为protected,则只能从该类的实例和子体访问它们(这应该是可以的,因为子体无论如何都可以访问实例变量,并且应该知道如何正确处理)

你可以

  def ==(other)
    @date_times == other.instance_eval{@date_times} and @frequencies == other.instance_eval{@frequencies}
  end

但不知怎的,我怀疑这没有抓住重点

这不是getters的重点吗?我不是有意要推翻你的评论,呵呵。我要说的是,要不惜一切代价避免获得成功。如果有某种形式的受保护访问或其他什么的话,那就太好了……嗯,可能有。对象状态应该尽可能私有。类用户不需要对对象发出命令的任何内容都应该对用户不可见。谢谢。。。这是有道理的。我选择了稍微不同的方式来实现它。。。见上图:)你说得对。它也在做同样的事情,但是看起来更好,特别是有很多属性(更少的重复)。
  def ==(other)
    @date_times == other.instance_eval{@date_times} and @frequencies == other.instance_eval{@frequencies}
  end