2

我正在编写一个 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
4

2 回答 2

4

如果您将时间和频率访问器设置为受保护,则只能从该类和后代的实例访问它们(这应该没问题,因为后代无论如何都可以访问实例变量并且应该知道如何正确处理它)。

class ReminderTimingInfo

  # …

protected
  attr_reader :times, :frequencies

end
于 2010-08-06T00:27:22.957 回答
2

你可以做

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

但不知何故,我怀疑这没有抓住重点!

于 2010-08-07T07:55:09.870 回答