Comparison of objects in ruby

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 a way to check if all public attributes in classes of the same type are equal?

+5
source share
4 answers
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
+6
source
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

Structdefines ==, eql?and hashfor you, so two Aaaare equal if their values ​​for aand bare equal. It also defines initializethat you can arbitrarily pass values ​​for aand bwhen creating an object ( Aaa.new(value_for_a, value_for_b)). And he determines to_ato return [a,b].

Struct.new , "" :

Aaa = Struct.new(:a, :b) do
  def c
    a+b
  end
end
Aaa.new(23,42).c #=> 65
+8

:

class Aaa
  def initialize(a,b,c)
    @a, @b, @c = a, b, c
  end
end

x = Aaa.new(1,2,3)
y = Aaa.new(1,2,3)
z = Aaa.new(1,2,3)
arr = [x,y,z]

x.instance_variables.map do |v|
  arr.map { |i| i.send(:instance_variable_get,v) }.uniq.size == 1
end.all?
  #=>true

z :

z = Aaa.new(1,2,4)

x.instance_variables.map do |v|
  arr.map { |i| i.send(:instance_variable_get,v) }.uniq.size == 1
end.all?
  #=> false
+1

Ruby hash. , , hash ruby:

Aaa attr_accessor: a,: b

def intialize (value_a, value_b)    @a = value_a    @b = value_b end

def hash (target)    @a.hash == target.a.hash && & @b.hash == target.b.hash

A = Aaa ( " ", " " ) B = Aaa ('', 'whoever') A.hash()

0

All Articles