为什么从哈希中删除键,从另一个哈希中删除它?

时间:2014-07-06 11:24:54

标签: ruby-on-rails hash key

为什么从哈希中删除密钥,也将其从其他哈希中删除?

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

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

输出:

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

此外:

 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"}

是参考吗?

1 个答案:

答案 0 :(得分:1)

因为#delete会改变原始的msg哈希值。如果您希望msg保持完整,请将重复传递给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