Ruby:是否将嵌套哈希转换为对象?

blpfk2vs  于 2022-11-04  发布在  Ruby
关注(0)|答案(6)|浏览(157)

我正在尝试将包含嵌套哈希的哈希转换为对象,以便可以使用点语法访问属性(包括嵌套属性)。
到目前为止,第一个哈希对象已被以下代码成功转换:

class Hashit
  def initialize(hash)
    hash.each do |k,v|
      self.instance_variable_set("@#{k}", v)
      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
    end
  end
end

问题是,这种方法不适用于嵌套哈希:

h = Hashit.new({a: '123r', b: {c: 'sdvs'}})
 => #<Hashit:0x00000006516c78 @a="123r", @b={:c=>"sdvs"}>

请注意,在输出中,@b={:c=>"sdvs"}没有被转换;它仍然是一个散列。
如何将嵌套哈希转换为对象?

zzlelutf

zzlelutf1#

您可以使用OpenStruct http://ruby-doc.org/stdlib-2.0.0/libdoc/ostruct/rdoc/OpenStruct.html

user = OpenStruct.new({name: "Jimmy Cool", age: "25"})
user.name #Jimmy Cool
user.age #25
uujelgoq

uujelgoq2#

另一种方法是使用JSON和OpenStruct,它们是标准的Ruby库:

irb:
> require 'JSON'
=> true

> r = JSON.parse({a: { b: { c: 1 }}}.to_json, object_class: OpenStruct)
=> #<OpenStruct a=#<OpenStruct b=#<OpenStruct c=1>>>

> r.a.b.c
=> 1
pdkcd3nj

pdkcd3nj3#

您需要添加递归性:

class Hashit
  def initialize(hash)
    hash.each do |k,v|
      self.instance_variable_set("@#{k}", v.is_a?(Hash) ? Hashit.new(v) : v)
      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
    end
  end
end

h = Hashit.new({a: '123r', b: {c: 'sdvs'}})

# => #<Hashit:0x007fa6029f4f70 @a="123r", @b=#<Hashit:0x007fa6029f4d18 @c="sdvs">>
gudnpqoy

gudnpqoy4#

Ruby有一个内置的数据结构OpenStruct来解决类似的问题。但是,仍然有一个问题。它不是递归的。所以,你可以像这样扩展OpenStruct类:


# Keep this in lib/open_struct.rb

class OpenStruct
  def initialize(hash = nil)
    @table = {}
    if hash
      hash.each_pair do |k, v|
        k = k.to_sym
        @table[k] = v.is_a?(Hash) ? OpenStruct.new(v) : v
      end
    end
  end

  def method_missing(mid, *args) # :nodoc:
    len = args.length
    if mname = mid[/.*(?==\z)/m]
      if len != 1
        raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
      end
      modifiable?[new_ostruct_member!(mname)] = args[0].is_a?(Hash) ? OpenStruct.new(args[0]) : args[0]
    elsif len == 0 # and /\A[a-z_]\w*\z/ =~ mid #
      if @table.key?(mid)
        new_ostruct_member!(mid) unless frozen?
        @table[mid]
      end
    else
      begin
        super
      rescue NoMethodError => err
        err.backtrace.shift
        raise
      end
    end
  end
end

下次使用OpenStruct时请记住require 'open_struct.rb'
现在您可以执行以下操作:

person = OpenStruct.new
person.name = "John Smith"
person.age  = 70
person.more_info = {interests: ['singing', 'dancing'], tech_skills: ['Ruby', 'C++']}

puts person.more_info.interests
puts person.more_info.tech_skills
u59ebvdq

u59ebvdq5#

当初始化对象时,可以检查v上的类型,并在new是另一个哈希值时调用new以获取新的Hashit

class Hashit
  def initialize(hash)
    hash.each do |k,v|
      self.instance_variable_set("@#{k}", v.is_a?(Hash) ? Hashit.new(v) : v)
      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
    end
  end
end

而之前的结果片段将是:

h = Hashit.new({a: '123r', b: {c: 'sdvs'}})
=> #<Hashit:0x007fa71421a850 @a="123r", @b=#<Hashit:0x007fa71421a5a8 @c="sdvs">>
23c0lvtd

23c0lvtd6#

如果我对问题的理解正确的话,这应该可以做到:

class Hashit
  def initialize(hash)
    convert_to_obj(hash)
  end

  private

  def convert_to_obj(h)
    h.each do |k,v|
      self.class.send(:attr_accessor, k)
      instance_variable_set("@#{k}", v) 
      convert_to_obj(v) if v.is_a? Hash
    end
  end
end

h = Hashit.new( { a: '123r',
      b: { c: 'sdvs', d: { e: { f: 'cat' }, g: {h: 'dog'} } } })
  #=> #<Hashit:0x000001018eee58 @a="123r",
  #     @b={:c=>"sdvs", :d=>{:e=>{:f=>"cat"}, :g=>{:h=>"dog"}}},
  #       @c="sdvs", @d={:e=>{:f=>"cat"}, :g=>{:h=>"dog"}},
  #       @e={:f=>"cat"}, @f="cat", @g={:h=>"dog"}, @h="dog">
h.instance_variables
  #=> [:@a, :@b, :@c, :@d, :@e, :@f, :@g, :@h]
Hashit.instance_methods(false)
  #=> [:a, :a=, :b, :b=, :c, :c=, :d, :d=, :e, :e=, :f, :f=, :g, :g=, :h, :h=]
h.d
  #=> {:e=>{:f=>"cat"}}
h.d = "cat"
h.d
  #=> "cat"

相关问题