如何用新值替换散列中的所有值? [英] How do I replace all the values in a hash with a new value?

查看:127
本文介绍了如何用新值替换散列中的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

假设我有class C 定义为:

  class C 
attr_accessor: dict
end

如何替换 h中的所有嵌套值以便它们现在 C 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 实例中。)

解决方案

  def convert_hash(h)
h.keys.each do | k |
如果h [k] .is_a?哈希
c = C.new
c.dict = convert_hash(h [k])
h [k] = c
结束
结束
h
结束

如果我们覆盖 inspect code> C 给出一个更友好的输出,如下所示:

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

然后以您的示例 h 这给出:

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

此外,如果您将初始化方法添加到 C 以设置 dict code $:

  def初始化(d =零)
self.dict = d
结束

然后你可以减少 convert_hash 只是 h [k] = C.new(convert_hash_h [k])


Let's say I have an arbitrarily deep nested Hash h:

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

And let's say I have a class C defined as:

class C
  attr_accessor :dict
end

How do I replace all nested values in h so that they are now C instances with the dict attribute set to that value? For instance, in the above example, I'd expect to have something like:

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

where <C @dict = ...> represents a C instance with @dict = .... (Note that as soon as you reach a value which isn't nested, you stop wrapping it in C instances.)

解决方案

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

If we override inspect in C to give a more friendly output like so:

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

and then run with your example h this gives:

puts convert_hash(h).inspect

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

Also, if you add an initialize method to C for setting dict:

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

then you can reduce the 3 lines in the middle of convert_hash to just h[k] = C.new(convert_hash_h[k])

这篇关于如何用新值替换散列中的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆