How Can I Convert Nested YAML to nested Arrays and OpenStructs in Ruby

拥有回忆 提交于 2020-01-05 09:48:48

问题


How should I convert a series of nested hashes (nested to arbitrary depth) to a series of nested OpenStructs? I'm loading in a big YAML file and I'm not enjoying accessing['everything']['like']['this'].

I have found a few partial solutions using Google, but I thought this would make a nice question here.

Here is one of the solutions I found from http://andreapavoni.com/blog/2013/4/create-recursive-openstruct-from-a-ruby-hash:

# deep_struct.rb
require 'ostruct'

class DeepStruct < OpenStruct
  def initialize(hash=nil)
    @table = {}
    @hash_table = {}

    if hash
      hash.each do |k,v|
        @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 to_h
    @hash_table
  end

end

Problem with this solution is that it doesn't take arrays into account.


回答1:


There is the solution (https://github.com/jsuchal/hashugar) i often use.

opts = Hashugar.new({:a => 1, 'b' => {:c => 2, :d => [3, 4, {:e => 5}]}})

But you also need to do:

opts.b.d.last.e

I do not understand how do you want to name array's getters. As Arup Rakshit sayed: give us yaml example and expected output or behavior.



来源:https://stackoverflow.com/questions/16990834/how-can-i-convert-nested-yaml-to-nested-arrays-and-openstructs-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!