Matheus Andrade
Matheus Andrade

Reputation: 27

Different obj_id but equal values in ruby?

I'm fairly new to ruby and am practicing it. However in this exercise I'm doing it creates two bank accounts using the same method and same values, and the program expects both to be equal. RSpec returns this to me:

Failure/Error: expect(conta1).to eql conta2

   expected: #<Conta:0x3161bc8 @numero="2303-2", @nome="Jose da Silva", @saldo=1000.1, @limite=500>
        got: #<Conta:0x31615f8 @numero="2303-2", @nome="Jose da Silva", @saldo=1000.1, @limite=500>

   (compared using eql?)

   Diff:
   @@ -1,4 +1,4 @@
   -#<Conta:0x3161bc8
   +#<Conta:0x31615f8
     @limite=500,
     @nome="Jose da Silva",
     @numero="2303-2",

The content of both the accounts are the same, but there's a conflict on the object_id, how do I resolve this?

Here is the code:

it "Two accounts with the same data should be equal" do
conta1 = cria_conta
conta2 = cria_conta
expect(conta1).to eql conta2
end

def cria_conta(numero="2303-2", nome="Jose da Silva", saldo=1000.10, limite=500)
Conta.new(numero: numero, nome: nome, saldo: saldo, limite: limite)
end

Also:

class Conta
attr_accessor :numero, :nome, :saldo, :limite

def initialize(arr)
    @numero = arr[:numero]
    @nome = arr[:nome]
    @saldo = arr[:saldo]
    @limite = arr[:limite]
end

def sacar(valor)
    possibilidade = false
    @@valor = valor
    if valor < @saldo
        @saldo -= valor
        possibilidade = true
    elsif valor > @limite
        @saldo -= valor
        @@saldo = @saldo
        possibilidade
    end
end

def no_limite?()
    if @@valor > @limite
        return true
    elsif @@valor < @limite
        return false
    end 
end

def depositar(valor)
    @saldo += valor
end

def ==(outra_conta)
self.conta == outra_conta

end end

I tried to define a a diffrent method for == but I was unsuccessful.

Upvotes: 0

Views: 49

Answers (1)

Chiwen Chen
Chiwen Chen

Reputation: 34

If you wants to only compare the attributes, not the object itself, here is the example code you might start with.

class Person
  attr_accessor :name, :id
  def initialize(id, name)
    @id = id
    @name = name
  end

  def ==(other_person)
    self.instance_variables.each do |method|
      method = method.to_s.gsub('@', '')
      return false if self.send(method) != other_person.send(method)
    end
    return true
  end
end

p1 = Person.new(1, 'alice')
p2 = Person.new(1, 'alice')
p3 = Person.new(1, 'tim')
puts p1 == p2 # true
puts p1 == p3 # false 

Upvotes: 1

Related Questions