How to replace all values ​​in a hash with a new value?

Say I have an arbitrarily deep nested hash h:

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

And let me have a class Cthat is defined as:

class C
  attr_accessor :dict
end

How to replace all nested values ​​in h, so that now they are instances Cwith the attribute dictset for this value? For example, in the above example, I 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 instance Cc @dict = .... (Note that once you reach a value that is not nested, you will stop wrapping it in instances C.)

+3
source share
2 answers
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

inspect C, , :

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])

+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>
# =>   }
# => }
+1

Source: https://habr.com/ru/post/1750937/


All Articles