【问题标题】:Is there a less awkward way to store a value in a Ruby hash?有没有一种不那么尴尬的方式来将值存储在 Ruby 哈希中?
【发布时间】:2017-10-17 13:58:07
【问题描述】:

我在 Ruby 中有一个哈希值,我正在向其中插入新的哈希值或向现有哈希值添加值。 我一直觉得 Ruby 有更好的方法来做到这一点:

map   # => { 1 => {:type => "humbug", :name => "grinch" }, 2 => {:type => 2 } }

  if map[key]
    map[key].store(:name, value)
  else
    map[key] = { name: value }
  end

我希望能够做类似的事情

map[key].store(:name, value) || map[key] = {name: value}

但如果map[key] 处没有value,当然会失败 ...建议?

【问题讨论】:

  • Ruby 中没有“地图”,有哈希。
  • @meagar 破产了!我整天都在使用 groovy ......其中到处都有地图:D

标签: ruby-on-rails ruby hashmap


【解决方案1】:

还有不那么尴尬的方法吗?

是的。

map[key] ||= {}
map[key].store(:name, value) # or map[key][:name] = value

或使用哈希缺失值处理程序之一。

map = Hash.new { |hash, key| hash[key] = {} }
# then set fearlessly, missing hashes will be auto-created.
map[key][:name] = value

【讨论】:

  • (map[key] ||= {}).store(:name, value).
  • @mudasobwa 我,我不会走这么远的。但每个人都有自己的:)
  • @SergioTulentsev 我会走那么远。我喜欢 Ruby 的优雅。
猜你喜欢
  • 2023-03-15
  • 2013-03-23
  • 2014-01-02
  • 1970-01-01
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多