簡體   English   中英

在Ruby中更新哈希鍵和值

[英]Updating Hash Key and Value in Ruby

這是示例代碼:

books = {
  Steve_Jobs: 10,
  Haryy_Potter: 7
}

我想更新此哈希的鍵及其值。

  1. 我不知道如何將Harry_Potter更改為Bill_Gates
  2. 對於值,我可以嘗試這樣:

     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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM