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 に答える