t56k
t56k

Reputation: 6981

Rails: make a nested hash-array type object

I'm trying to make a nested (and thus sorted) array of hashes like so:

[{ stack: 'stack name', id: 1,
    boxes: [{
      box: 'whatever box',
      id: 1,
      vars: [{
        var: 'some name',
        id: 22,
      }, 
      { var: 'another name',
        id: 4 
      }]
    }, {
      box: 'another box',
      id: 99,
      vars: [{
        var: 'another',
        id: 999
      }]
    }    
  }]
}]

The method I've come up with so far is this which doesn't work but I'm totally stack as to how to nest these objects to maintain their hierarchy (a Stack can have many Boxes, a Box can have many TemplateVariables.

master = []
@template.stacks.alphabetised.each_with_index do |stack, i|
  master << { stack: stack.name, id: stack.id }
  stack.boxes.indexed.each_with_index do |box, j|
    master[i] = { box: box.name, id: box.id }
    box.template_variables.indexed.each do |var|
      master[i][j] = { var: var.name, id: var.id }
    end
  end
end
master

This seems to return nothing despite those objects definitely being there (and I know my structure is off, too). Am I doing something wrong?

Upvotes: 0

Views: 148

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54223

You could use nested maps :

################################################
# Initialization code. Different from yours.
def stacks
  Array.new(2){|i| "Stack #{i+1}"}
end

@box_id = 0
def boxes
  Array.new(2){ "Box #{@box_id += 1}"}
end

@var_id = 0
def vars
  Array.new(2){ "Var #{@var_id += 1}"}
end
################################################

stack_data = stacks.map.with_index do |stack,i|
  box_data = boxes.map.with_index do |box,j|
    var_data = vars.map.with_index do |var,k|
      {var: var, id: k}
    end
    {box: box, id: j, vars: var_data}
  end
  {stack: stack, id: i, boxes: box_data}
end

require 'pp'
pp stack_data

It outputs :

[{:stack=>"Stack 1",
  :id=>0,
  :boxes=>
   [{:box=>"Box 1",
     :id=>0,
     :vars=>[{:var=>"Var 1", :id=>0}, {:var=>"Var 2", :id=>1}]},
    {:box=>"Box 2",
     :id=>1,
     :vars=>[{:var=>"Var 3", :id=>0}, {:var=>"Var 4", :id=>1}]}]},
 {:stack=>"Stack 2",
  :id=>1,
  :boxes=>
   [{:box=>"Box 3",
     :id=>0,
     :vars=>[{:var=>"Var 5", :id=>0}, {:var=>"Var 6", :id=>1}]},
    {:box=>"Box 4",
     :id=>1,
     :vars=>[{:var=>"Var 7", :id=>0}, {:var=>"Var 8", :id=>1}]}]}]

Upvotes: 1

Related Questions