Sergey Shirnin
Sergey Shirnin

Reputation: 13

Ruby instance variable and hash key - how it works

Please someone tell me how it works? Setting of hash key with the same name with instance variable @remote take affect on its own value... How?

@remote = { url: '/user/validate', type: :post }
@config = {}
@config[:remote] = {}

def test
  @config[:remote] = @remote

  data = { data: 'some data' }
  @config[:remote][:data] = data
end

# call method test
test

p @remote.to_s # => "{:url=>\"/user/validate\", :type=>:post, :data=>{:data=>\"some data\"}}"
p @config.to_s # => "{:remote=>{:url=>\"/user/validate\", :type=>:post, :data=>{:data=>\"some data\"}}}"

Upvotes: 0

Views: 753

Answers (1)

Phlip
Phlip

Reputation: 5343

Ruby is one of many languages that distinguish "immediate values" and "reference values".

If I say x = 5; y = x; y = 6, then x is an immediate value, and still contains 5, not 6.

But if I say x = { value: 5 }, then x is a reference to a hash object. When I say y = x then y refers to the same hash object as x does. So y[:value] = 6 will make x[:value] == 6.

To prevent this behavior, look up "ruby deep copy", and use y = x.dup.

Upvotes: 1

Related Questions