gpt4 book ai didi

ruby - 在不需要公开私有(private)字段的情况下制作一个 equals 方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:20 24 4
gpt4 key购买 nike

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

最佳答案

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

class ReminderTimingInfo

# …

protected
attr_reader :times, :frequencies

end

关于ruby - 在不需要公开私有(private)字段的情况下制作一个 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3420146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com