user2503775
user2503775

Reputation: 4367

why removing key from hash ,removes it also from another hash?

why removing key from hash ,removes it also from the other hash?

msg = { key1: "XXX",key2: 'xxx' }
send_msg(msg)
send_msg(msg)

def send_message(msg)
  p msg
  msg.delete(:key1)
end

The output:

=> { key1: "XXX",key2: 'xxx' }
=> { key2: 'xxx' }

Also:

 irb(main):023:0> a = { key1: "XXX",key2: 'xxx' }
    => {:key1=>"XXX", :key2=>"xxx"}
    irb(main):024:0> b=a
    => {:key1=>"XXX", :key2=>"xxx"}
    irb(main):025:0> a.delete(:key1)
    => "XXX"
    irb(main):026:0> a
    => {:key2=>"xxx"}
    irb(main):027:0> b
    => {:key2=>"xxx"}

Is it a reference?

Upvotes: 0

Views: 41

Answers (1)

Gosha A
Gosha A

Reputation: 4570

Because #delete mutates the original msg hash. If you want msg to stay intact, pass its duplicate to send_msg:

msg = { key1: "XXX",key2: 'xxx' }
send_msg(msg.dup)
send_msg(msg.dup)

def send_message(msg)
  p msg
  msg.delete(:key1)
end

Upvotes: 1

Related Questions