在Ruby中,哈希(Hash)是一种可变的、无序的键值对集合。要更新哈希中的数据,可以使用以下方法:
hash = { "a" => 1, "b" => 2, "c" => 3 }
hash["a"] = 10
puts hash # 输出:{"a"=>10, "b"=>2, "c"=>3}
[]=
运算符更新:hash = { "a" => 1, "b" => 2, "c" => 3 }
hash["a"] = 10
puts hash # 输出:{"a"=>10, "b"=>2, "c"=>3}
update
方法更新哈希:hash = { "a" => 1, "b" => 2, "c" => 3 }
hash.update("a" => 10)
puts hash # 输出:{"a"=>10, "b"=>2, "c"=>3}
merge
方法更新哈希:hash = { "a" => 1, "b" => 2, "c" => 3 }
hash.merge!("a" => 10)
puts hash # 输出:{"a"=>10, "b"=>2, "c"=>3}
注意:update
方法会修改原始哈希,而merge
方法会返回一个新的哈希,原始哈希保持不变。
[]=
运算符更新多个键值对:hash = { "a" => 1, "b" => 2, "c" => 3 }
hash["a"] = 10
hash["b"] = 20
hash["c"] = 30
puts hash # 输出:{"a"=>10, "b"=>20, "c"=>30}
merge
方法更新多个键值对:hash = { "a" => 1, "b" => 2, "c" => 3 }
hash.merge!("a" => 10, "b" => 20, "c" => 30)
puts hash # 输出:{"a"=>10, "b"=>20, "c"=>30}
hash = { "a" => 1, "b" => 2, "c" => 3 }
hash.merge! do |key, old_value, new_value|
if key == "a"
new_value * 2
else
old_value
end
end
puts hash # 输出:{"a"=>20, "b"=>2, "c"=>3}
这些方法允许您根据需要更新哈希中的数据。