0

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

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] || { }

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

非常感谢

4

2 回答 2

1

你可以这样做:

class Hash
  def value_for((*keys, last), value)
    _h = nil
    keys.inject(self){|h, k| _h = h[k] ||= {}}
    _h[last] = value
  end
end
于 2013-01-04T15:00:38.740 回答
0

这是一个工作代码示例:

class Hash
  def value_for(keys, value)
    common = {}
    common[keys.last] = value
    (keys.size - 2).downto(0).each do |index|
      common[keys[index]] = {keys[index+1] => common[keys[index+1]]}
    end 
    return common
  end 
end

您的代码的问题是:

  1. 要实现您尝试做的事情,您需要以相反的顺序遍历键,因为 key[i] 取决于 key[i+1] 的值
  2. 您需要为每个键创建一个新的哈希,而common[keys.shift]实际上是一个值,您应该添加另一层嵌套。

希望这可以帮助。

于 2013-01-04T14:45:56.230 回答