我正在编写一个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
答案 0 :(得分:4)
如果您将时间和频率访问者设置为受保护,那么它们只能从该类和后代的实例访问(这应该没问题,因为后代无论如何都可以访问实例变量,并且应该知道如何正确处理它)。
class ReminderTimingInfo
# …
protected
attr_reader :times, :frequencies
end
答案 1 :(得分:2)
你可以做到
def ==(other)
@date_times == other.instance_eval{@date_times} and @frequencies == other.instance_eval{@frequencies}
end
但不知怎的,我怀疑那是错过了重点!