代码之家  ›  专栏  ›  技术社区  ›  Alex Baranosky

在不需要公开私有字段的情况下生成equals方法

  •  2
  • Alex Baranosky  · 技术社区  · 15 年前

    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
    
    2 回复  |  直到 13 年前
        1
  •  4
  •   Zargony    15 年前

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

    class ReminderTimingInfo
    
      # …
    
    protected
      attr_reader :times, :frequencies
    
    end
    
        2
  •  2
  •   Andrew Grimm atk    15 年前

    你能做到的

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

    但不知怎么的,我怀疑这是错的!