对嵌套哈希使用Ruby select方法

时间:2018-07-23 02:07:42

标签: ruby

我有一个从HTML解析出来的哈希

散列看起来像这样,除了它有38个嵌套的散列

@ProductionInfoDataHash = {
    0=>{:name=>"Name", :primSegment=>"Primary Segment", :unitsSold=>"Units Sold", :unitsInventory=>"Unit Inven tory", :revisionDate=>"Revision Date", :age=>0.0, :mtbf=>"MTBF", :pfmnCoord=>0.0, :sizeCoord=>0.0, :price=>"rice", :matirialCost=>"aterial Cost", :laborCost=>"abor Cost", :contrMarg=>0.0, :overtime=>0.02, :automation=>"Auto mation Next Round", :capacity=>"Capacity Next Round", :plantUtiliz=>0.0},
    1=>{:name=>"", :primSegment=>"", :unitsSold=>"", :unitsInventory=>"", :revisionDate=>"", :age=>0.0, :mtbf=>"", :pfmnCoord=>0.0, :sizeCoord=>0.0, :price=>nil, :matirialCost=>nil, :laborCost=>nil, :contrMarg=>0.0, :overtime=>0.0, :automation=>"", :capacity=>"", :plantUtiliz=>0.0}, 
    2=>{:name=>"Able", :primSegment=>"Trad", :unitsSold=>"999", :unitsInventory=>"189", :revisionDate=>"11/21/2015", :age=>3.1, :mtbf=>"17500", :pfmnCoord=>5.5, :sizeCoord=>14.5, :price=>"28.00", :matirialCost=>"11.59", :laborCost=>"7.49", :contrMarg=>0.29, :overtime=>0.0, :automation=>"4.0", :capacity=>"1,800", :plantUtiliz=>0.66},
    3=>{:name=>"Acre", :primSegment=>"Low", :unitsSold=>"1,763", :unitsInventory=>"39", :revisionDate=>"5/25/2014", :age=>4.6, :mtbf=>"14000", :pfmnCoord=>3.0, :sizeCoord=>17.0, :price=>"21.00", :matirialCost=>"7.81", :laborCost=>"7.12", :contrMarg=>0.27, :overtime=>0.3, :automation=>"5.0", :capacity=>"1,400", :plantUtiliz=>1.29},
    4=>{:name=>"Adam", :primSegment=>"High", :unitsSold=>"366", :unitsInventory=>"40", :revisionDate=>"4/19/2017", :age=>1.7, :mtbf=>"23000", :pfmnCoord=>8.0, :sizeCoord=>12.0, :price=>"38.00", :matirialCost=>"15.98", :laborCost=>"8.57", :contrMarg=>0.33, :overtime=>0.0, :automation=>"3.0", :capacity=>"900", :plantUtiliz=>0.45}
}

我想基于:primSegment键的值遍历嵌套的哈希。

我代码的相关部分是

def productionInfoData_to_Sheet

    g  = @ProductionInfoDataHash.select{ |item| item[:primSegment] == "Trad" } # get all nested hashes that have a [:primSegment] == "Trad"
    puts g                                                                 
 end

我得到了错误 `[]':不会将Symbol隐式转换为Integer(TypeError)

2 个答案:

答案 0 :(得分:1)

您没有在选择语句中包含密钥,请尝试

@ProductionInfoDataHash.select{ |index, item| item[:primSegment] == "Trad" }

答案 1 :(得分:1)

您需要在选择查询中考虑键和值。

喜欢

@ProductionInfoDataHash.select { |key, value| value[:primSegment] == 'Trad' }

此外,我建议您检查最常用的ruby style guide

您不应在ProductionInfoDataHash之类的变量上使用CamelCase