Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create Ruby Class with same object id

I need to create a class where if the attribute value is the same it does not generate a new object id, example:

result:

described_class.new('01201201202')

<PixKey:0x00007eff5eab1ff8 @key="01201201202">

if i run it again with the same value it should keep the same object id

0x00007eff5eab1ff8

is similar behavior with the symbol

test:

describe '#==' do
  let(:cpf)   { described_class.new('01201201202') }

  it 'verifies the key equality' do
    expect(cpf).to eq described_class.new('01201201202')
  end
 end

Running the test shows an error, because the obejct id changes:

expected: #<PixKey:0x00007eff5eab1ff8 @key="01201201202">
got: #<PixKey:0x00007eff5eab2070 @key="01201201202">

Class:

class PixKey
  def init(key)
    @key = key
  end
end
like image 530
Davi Luis Avatar asked Jan 18 '26 18:01

Davi Luis


1 Answers

The other answers are fine, but they are a little more verbose than needed and they use class variables, which I find to be a confusing concept because of how they are shared among various classes.

class PixKey
  @instances = {}
  def self.new(id)
    @instances[id] ||= super(id)
  end
  def initialize(id)
    @key = id
  end
end

p PixKey.new(1)
p PixKey.new(2)
p PixKey.new(2)
p PixKey.new(1)
like image 172
David Grayson Avatar answered Jan 21 '26 07:01

David Grayson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!