3

假设我有一个任意深度的嵌套 Hash h

h = {
  :foo => { :bar => 1 },
  :baz => 10,
  :quux => { :swozz => {:muux => 1000}, :grimel => 200 }
  # ...
}

假设我有一个类C定义为:

class C
  attr_accessor :dict
end

如何替换所有嵌套值,h以便它们现在是属性设置为该值C的实例?dict例如,在上面的例子中,我希望有类似的东西:

h = {
  :foo => <C @dict={:bar => 1}>,
  :baz => 10,
  :quux => <C @dict={:swozz => <C @dict={:muux => 1000}>, :grimel => 200}>
  # ...
}

其中<C @dict = ...>代表一个C实例@dict = ...。(请注意,一旦你达到一个非嵌套的值,你就停止在C实例中包装它。)

4

2 回答 2

1
def convert_hash(h)
  h.keys.each do |k|
    if h[k].is_a? Hash
      c = C.new
      c.dict = convert_hash(h[k])
      h[k] = c
    end
  end
  h
end

如果我们覆盖inspectinC以提供更友好的输出,如下所示:

def inspect
  "<C @dict=#{dict.inspect}>"
end

然后使用您的示例运行,h这给出:

puts convert_hash(h).inspect

{:baz=>10, :quux=><C @dict={:grimel=>200, 
 :swozz=><C @dict={:muux=>1000}>}>, :foo=><C @dict={:bar=>1}>}

此外,如果您添加一个initialize方法来C设置dict

def initialize(d=nil)
  self.dict = d
end

那么你可以将中间的3行减少convert_hash到刚刚h[k] = C.new(convert_hash_h[k])

于 2010-06-21T00:24:16.447 回答
1
class C
  attr_accessor :dict

  def initialize(dict)
    self.dict = dict
  end
end

class Object
  def convert_to_dict
    C.new(self)
  end
end

class Hash
  def convert_to_dict
    Hash[map {|k, v| [k, v.convert_to_dict] }]
  end
end

p h.convert_to_dict
# => {
# =>   :foo => {
# =>     :bar => #<C:0x13adc18 @dict=1>
# =>   },
# =>   :baz => #<C:0x13adba0 @dict=10>,
# =>   :quux => {
# =>     :swozz => {
# =>       :muux => #<C:0x13adac8 @dict=1000>
# =>     },
# =>     :grimel => #<C:0x13ada50 @dict=200>
# =>   }
# => }
于 2010-06-21T10:31:23.067 回答