如何将嵌套YAML转换为Ruby中的嵌套数组和OpenStruc

如何将嵌套YAML转换为Ruby中的嵌套数组和OpenStruc

本文介绍了如何将嵌套YAML转换为Ruby中的嵌套数组和OpenStructs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何将一系列嵌套散列(嵌套到任意深度)转换为一系列嵌套的OpenStructs?我正在加载一个大的YAML文件,我不喜欢访问[ '一切'] [ '象'] [ '这个']



我发现了一些使用Google的部分解决方案,但我认为这会提出一个很好的问题。



以下是我从:

 #deep_struct.rb 
需要'ostruct'

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

如果哈希
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)
结束
结束
结束

结束to_h
@hash_table
结束

结束

这个解决方案的问题在于它不考虑数组。

解决方案

有解决方案()我经常使用。

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

但是你也需要这样做:

opts.bdlast.e



我不明白你想如何命名数组的getter。正如Arup Rakshit所说的:给我们一个例子和预期的输出或行为。

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.

解决方案

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.

这篇关于如何将嵌套YAML转换为Ruby中的嵌套数组和OpenStructs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:38