[英]Updating Hash Key and Value in Ruby
這是示例代碼:
books = {
Steve_Jobs: 10,
Haryy_Potter: 7
}
我想更新此哈希的鍵及其值。
Harry_Potter
更改為Bill_Gates
。 對於值,我可以嘗試這樣:
books[:Harry_Potter] = 10
我嘗試過books.update[:Harry_Potter] = "Bill_Gates".to_sym
,但是它不起作用。
這個怎么樣?
books[:Bill_Gates] = books.delete(:Harry_Potter)
change = { "Harry_Potter" => "Bill_Gates" }
books = Hash[ books.map { |k, v| [change[k] || k, v] } ]
將您想要更改的鍵和您想要更改的值放在更改哈希中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.