Tim Hunter
7/4/2006 2:34:00 PM
Just Another Victim of the Ambient Morality wrote:
> I have some problems that I'm sure must be routine for Ruby developers
> but I'm a little stumped on how to solve them. Any help is greatly
> appreciated!
>
> My first problem is that I have a class and I want to define some
> operators, like equality. It's a simple class and its operators are equally
> simple. Equality is simple the equality of the member variables of my
> class. So, I have code that looks something like this:
>
> class Object
> attr_accessor :first, :second, :third
>
> def initialize (first, second, third)
> @first, @second, @third = first, second, third
> end
>
> def == (right) # should this be Eql?
> bool = true
> [:first, :second, :third].each do |member|
> bool = (bool and (method(member).call ==
> right.method(member).call))
> end
> bool
> end
> end
>
> What I'm trying to do is automate iterating over my member variables
> performing a cumulative equality test. The best I was able to come up with
> was a single list of members but there must be some way, through inspection,
> to programmatically iterator over them to do this test. Also, it looks like
> there might be something a little more efficient than calling "method" on
> each member and then calling "call" on each method object returned. Is
> there?
How about something like this:
class Foo
include Comparable
attr_accessor :a, :b, :c
def initialize(a, b, c)
@a, @b, @c = a, b, c
end
def <=>(other)
[@a, @b, @c] <=> [other.a, other.b, other.c]
end
end
The Comparable module adds ==, <, >, and other comparison methods to Foo
by calling Foo's <=> method.
>
> My second problem is that I would like to put this simple object in a
> Set (as broken as it may be). How do I do this? I know this doesn't
> magically just work. I have to define something like a "hash" method but I
> don't know what hash is supposed to return, exactly, for things like Set and
> Hash to work. Can someone explain this to me?
The hash and eql? method in Object will be fine for your class. You
don't need to override them unless you have special needs.
>
> Thank you for your responses! I will use them to be a better Ruby
> programmer...
>
>