Rails:在do循环中未将值赋给数组

时间:2017-08-17 17:14:03

标签: ruby-on-rails arrays

我有一个名为components

的数组
components = [
   {
      :name => "Component 1",
      :order => "1"
   },
   {
      :name => "Component 2",
      :order => "2"
   },
   {
      :name => "Component 3",
      :order => "3"
   },
   {
      :name => "Component 4",
      :order => "4"
   }
]

另一个名为subcomponent

的数组
subcomponents = [
   {
      :name => "Subcomponent 1A",
      :order => "1A"
   },
   {
      :name => "Subomponent 1B",
      :order => "1B"
   },
   {
      :name => "Component 2A",
      :order => "2A"
    },
   {
      :name => "Component 4A",
      :order => "4A"
   }
]

我试图得到它,以便子组件出现在组件对象下面,如果它们是该对象的子组件。这是预期的输出:

components = [
   {
      :name => "Component 1",
      :order => "1",
      :subcomponents => [
         {
            :name => "Subcomponent 1A",
            :order => "1A"
         },
         {
            :name => "Subomponent 1B",
            :order => "1B"
         }
      ]
   },
   {
      :name => "Component 2",
      :order => "2",
      :subcomponents => [ 
         {
            :name => "Component 2A",
            :order => "2A"
         }
      ]
   },
   {
      :name => "Component 3",
      :order => "3",
      :subcomponent => []
   },
   {
      :name => "Component 4",
      :order => "4",
      :subcomponent => [
         {
            :name => "Component 4A",
            :order => "4A"
         }
      ]
   }
]

我已经创建了一个循环来尝试这样做:

components.each do |c|
      c.class.module_eval { attr_accessor :subcomponents}
      c.subcomponents = []

      subcomponents.each do |s|
        if /#{c["order"]}[A-Z]/ =~ s["order"]
          #This is never assigned but it does make it into this statement 
          c.subcomponents << s
        end
      end 

     puts c.subcomponents.to_s # This prints []
end

当我输入我的代码注释时,即使进入if语句,子组件也永远不会被分配回component.subcomponents数组。

我是否遗漏了component.subcomponents的范围不再可访问或范围不同的内容?

我应该做些什么来确保我可以分配值component.subcomponents

3 个答案:

答案 0 :(得分:1)

components.each do |c|
  c[:subcomponents] = []
  subcomponents.each do |s|
    c[:subcomponents] << s if /#{c[:order]}[A-Z]/ =~ s[:order]
  end 
end

答案 1 :(得分:0)

希望这项工作。

components.each do |component|
  component[:subcomponents] = []
end

subcomponents.each do |subcomponent|
  order = subcomponent[:order][/\d+/]

  components.each do |component|
    if order == component[:order]
      component[:subcomponents] << subcomponent
    end
  end
end

答案 2 :(得分:0)

您可以使用以下代码O(n)执行此操作:

subcomponent_hash = Hash.new { |h, k| h[k] = [] }
subcomponents.each do |sc|
  order = sc[:order][/\d+/]
  subcomponent_hash[order] << sc
end

components.each do |c|
  c[:subcomponents] = subcomponent_hash[c[:order]]
end