2
votes

I'm writing a Ruby class, and want to override the == method. I want to say something like:

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

How can I do this without making both times and frequencies publicly viewable?

FOLLOW UP:

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
Isn't that the point of getters? - NullUserException
didn't mean to upvote your comment, hehe. I'd say getters are something to be avoided at all costs. It would be nice if there were some form of protected access or something...Hmmm maybe there is. - Alex Baranosky
Object state should be as private as possible. Anything the class user doesn't need to make a command to the object should be invisible to the user. - Alex Baranosky

2 Answers

4
votes

If you set times and frequencies accessors to protected, they'll be only accessible from instances of that class and descendants (which should be ok, since descendants can access the instance variables anyway and should know how to handle it correctly).

class ReminderTimingInfo

  # …

protected
  attr_reader :times, :frequencies

end
2
votes

You could do

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

But somehow I suspect that that's missing the point!