在Ruby中,哈希(Hash)是一種可變的、無序的鍵值對集合。要更新哈希中的數(shù)據(jù),可以使用以下方法:
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}
這些方法允許您根據(jù)需要更新哈希中的數(shù)據(jù)。