views:

45

answers:

2

Consider this:

class Aaa
  attr_accessor :a, :b
end

x = Aaa.new
x.a, x.b = 1,2
y = Aaa.new
y.a, y.b = 1,2

puts x == y #=>false

Is there some way to check if all public attributes are equal in classes of same type?

+3  A: 
Aaa = Struct.new(:a, :b)

x = Aaa.new
x.a, x.b = 1,2
y = Aaa.new
y.a, y.b = 1,2

x == y #=> true

Struct defines ==, eql?, and hash for you, so that two Aaas are equal, if their values for a and b are equal. It also defines initialize so that you can optionally pass in the values for a and b when creating the object (Aaa.new(value_for_a, value_for_b)). And it defines to_a to return [a,b].

You can also use Struct.new with a block to define additional methods, so you have the full power of a "normal" class:

Aaa = Struct.new(:a, :b) do
  def c
    a+b
  end
end
Aaa.new(23,42).c #=> 65
sepp2k
This seems fine but I need this functionality for objects, anyway nice response I didn't know about Structs
dfens
@dfens: Those are objects. `Struct.new` is just a factory method for classes. You'd get the exact same behavior if you'd define `Aaa` using the `class` keyword and then defined `==` etc. yourself.
sepp2k
+1  A: 
class Aaa
  attr_accessor :a, :b

  def ==(other)
    return self.a == other.a && self.b == other.b
  end
end

x = Aaa.new
x.a,x.b = 1,2
y = Aaa.new
y.a,y.b = 1,2
y = Aaa.new
y.a,y.b = 1,2
z = Aaa.new
z.a,z.b = 1,3

x == y # => true
x == z # => false
Jason Noble
But what if i want to do this using other classes? Or if there are 100 attributes?
dfens
In your ==(other) method, you could do self.instance_variables.each do |ivar| self.ivar == other.ivar endYou may want to look at === as well.
Jason Noble
worked for me, thanks
dfens