ruby 嵌套哈希

标签 ruby algorithm hashmap nested

我只是有一个简单的问题,请考虑这段代码:

class Hash
  def value_for(keys, value)
    common = self
    while keys.size > 1 and !common.nil?
      common = common[keys.shift] || { }
    end
    common[keys.last] = value
  end
end

通过这段代码,我希望能够通过传递嵌套节点数组和应该分配的值来创建嵌套哈希。

它应该像下面这样工作:

hash = {
  "message" => "hello world"
}

hash.value_for [ "nested", "message" ], "hello world"

hash
#=> {
       "message" => "hello world",
       "nested" => {
         "message" => "hello world"
       }
    }

hash.value_for [ "second", "nested", "message" ], "hello world"

hash
#=> {
       "message" => "hello world",
       "nested" => {
         "message" => "hello world"
       },
       "second" => {
         "nested" => {
           "message" => "hello world"
         }
       }
    }

出于某种原因,我的代码在创建新哈希时不起作用。我怀疑它与 common = common[keys.shift] || 有关{}

有人可以帮帮我吗? 我觉得我错过了一些愚蠢的东西......

非常感谢

最佳答案

你可以这样做:

class Hash
  def value_for((*keys, last), value)
    _h = nil
    keys.inject(self){|h, k| _h = h[k] ||= {}}
    _h[last] = value
  end
end

关于 ruby 嵌套哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14158987/

相关文章:

java - HashMap 如何在不调用 equals 方法的情况下替换键的值

ruby-on-rails - 在 Ruby/Rails 中使用特定排序规则对值进行排序

ruby-on-rails - Mavericks,RBENV,你的 Ruby 版本是 2.0.0,但是你的 Gemfile 指定了 2.1.1

java - 如何在java中将 HashMap 的哈希值转换为json

javascript - 计算两点之间的最短路径

algorithm - 如何在风景上模仿水

java - 比较 Java 中列表映射中的每个对象

ruby - 如何从字符串的开头获取子字符串,直到 Ruby 中字符串中特定索引之前的字符的最后一次出现

ruby-on-rails - 如何在 heroku worker 中捕获内存配额异常

Python数线簇练习