Hao's Blog

Software Engineer

Create Multiple Varariables With Differentreferences in Ruby

| Comments

Today I had a bug in ruby which I do not quite understand, and it turned out to be reference issue in ruby.

First, I tried something like this and intended to create 4 variables for the same values, but different objects

1
a, b, c ,d = [Object.new] * 4

This turns out to be a, b, c, d refers to the same object

1
2
a.object_id == b.object_id
#=> true

So the correct way should be:

1
a, b, c, d = Object.new, Object.new, Object.new, Object.new

Comments