0

目标:OpenStruct 对象的值应打印为散列而不是对象

可能的解决方案:覆盖 OpenStruct 类的 getter

MyOpenStruct覆盖和的。new_to_h[]OpenStruct

class MyOpenStruct < OpenStruct
    def initialize(object=nil)
        @table = {}
        @hash_table = {}

        if object
            object.each do |k,v|
                if v.is_a?(Array)
                    other = Array.new()
                    v.each { |e| other.push(self.class.new(entry)) }
                    v = other
                end
                @table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
                @hash_table[k.to_sym] = v
                new_ostruct_member(k)
            end
        end
    end

    def [](val)
        @hash_table[val.to_sym]
    end
end

但是压倒一切[]并没有任何区别。例如

irb(main):007:0> temp = MyOpenStruct.new({"name"=>"first", "place"=>{"animal"=>"thing"}})
=> #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">>
irb(main):008:0> temp.name
=> "first"
irb(main):009:0> temp.place
=> #<MyOpenStruct animal="thing">
irb(main):010:0> temp["place"]
=> {"animal"=>"thing"}
irb(main):011:0> temp[:place]
=> {"animal"=>"thing"}
irb(main):012:0> temp
=> #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">>

只有当我使用[]哈希访问密钥时才会返回!

我该如何纠正这个?

4

2 回答 2

2

如果您将其作为哈希返回,我认为创建嵌套的 OpenStruct 是没有意义的。这就是 OpenStruct 的工作方式:

require 'ostruct'
struct = OpenStruct.new(name: 'first', place: { animal: 'thing' })
struct.place
# => {:animal=>"thing"}
struct.place[:animal]
# => "thing"
struct.place.animal
# => NoMethodError: undefined method `animal' for {:animal=>"thing"}:Hash

所以,如果你想使用点符号来获取struct.place.animal,你需要像你一样创建嵌套的 OpenStruct 对象。但是,正如我所说,您不需要重写该[]方法。使用你的类而不覆盖[]我得到这个:

struct = MyOpenStruct.new(name: 'first', place: { animal: 'thing' })
# => #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">> 
struct.place
# => #<MyOpenStruct animal="thing"> 
struct.place.animal
# => "thing" 

无论如何,如果您真的想让点符号按您的要求工作,您可以覆盖该new_ostruct_member方法,该方法在内部用于在设置 OpenStruct 对象时创建动态属性。你可以尝试这样的事情,但我不推荐

class MyOpenStruct < OpenStruct
  def initialize(object=nil)
    @table = {}
    @hash_table = {}

    if object
      object.each do |k,v|
        if v.is_a?(Array)
          other = Array.new()
          v.each { |e| other.push(self.class.new(entry)) }
          v = other
        end
        @table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
        @hash_table[k.to_sym] = v
        new_ostruct_member(k)
      end
    end
  end

  def [](val)
    @hash_table[val.to_sym]
  end

  protected

  def new_ostruct_member(name)
    name = name.to_sym
    unless respond_to?(name)
      # use the overrided `[]` method, to return a hash
      define_singleton_method(name) { self[name] }
      define_singleton_method("#{name}=") { |x| modifiable[name] = x }
    end
    name
  end
end

struct = MyOpenStruct.new(name: 'first', place: { animal: 'thing' })
# => #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">> 
struct.place
# => {:animal=>"thing"} 
struct.place[:animal]
# => "thing" 
于 2015-10-28T20:16:42.603 回答
1

@Doguita 的回答在所有方面都是正确的。我只是想回答你的问题“如果那不可能,那么我可以打印整个对象的哈希temp吗?” 是的你可以。您只需要重写to_h以递归地遍历您的键和值并将 MyOpenStruct 的实例转换为哈希:

def to_h
  @table.each_with_object({}) do |(key, val), table|
    table[key] = to_h_convert(val)
  end
end

private
def to_h_convert(val)
  case val
  when self.class
    val.to_h
  when Hash
    val.each_with_object({}) do |(key, val), hsh|
      hsh[key] = to_h_convert(val)
    end
  when Array
    val.map {|item| to_h_convert(item) }
  else
    val
  end
end
于 2015-10-28T20:49:46.310 回答