Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Don't the solutions work? –  Sergio Tulentsev Jun 7 '13 at 18:40
    
@SergioTulentsev Yep, they appear to be OK, but I'm interested to see other solutions people are using, and it's a question that hasn't been asked. –  Pedr Jun 7 '13 at 18:41
3  
Why don't you post a couple of them and also tell why don't you like them? –  Sergio Tulentsev Jun 7 '13 at 18:42
    
Which behavior do you expect for arrays? –  Thiago Lewin Jun 7 '13 at 19:28
    
@tlewin Deserialised YAML is made of Arrays and Hashes, so I would want Arrays and OpenStructs. –  Pedr Jun 7 '13 at 19:35

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.