如何访问属于特定值的嵌套值

时间:2018-06-29 14:37:03

标签: json ruby

我无法访问某些数据。

我有这个文件:

SUPPLIERS = [
{ name: "FunePlus", advitam_grade: 3, works: [ { type: "embalming", price: 350 }, {type: "transport_before_casketing", price: 450} ]},
{ name: "FuneTop", works: [ { type: "graving", price: 10 } ]},
{ name: "FuneTruc", advitam_grade: 5, works: [ { type: "embalming", price: 750 }]},
{ name: "FuneCorp", advitam_grade: 2, works: [ { type: "digging", price: 350 }]}
]



class SelectSupplier
  def self.global_grade(name)

  end
end

SelectSupplier.global_grade("FunePlus")

当我调用方法global_grade时,我想加入一个特定的名称,然后返回相关的值。

这是我想要的输出:

SelectSupplier.global_grade("FunePlus")
 :advitam_grade=>3, :works=>[{:type=>"embalming", :price=>350}, {:type=>"transport_before_casketing", :price=>450}]}

你们中的一些人对我该怎么做有任何想法吗?

2 个答案:

答案 0 :(得分:2)

您可以使用Array#find方法来做到这一点:

SUPPLIERS = [
{ name: "FunePlus", advitam_grade: 3, works: [ { type: "embalming", price: 350 }, {type: "transport_before_casketing", price: 450} ]},
{ name: "FuneTop", works: [ { type: "graving", price: 10 } ]},
{ name: "FuneTruc", advitam_grade: 5, works: [ { type: "embalming", price: 750 }]},
{ name: "FuneCorp", advitam_grade: 2, works: [ { type: "digging", price: 350 }]}
]



class SelectSupplier
  def self.global_grade(name)
      SUPPLIERS.find {|x| x[:name] == name }
  end
end

SelectSupplier.global_grade("FunePlus")

这将返回与您的name参数匹配的第一个哈希

答案 1 :(得分:0)

@John告诉您如何提取所需的哈希。如果您希望多次执行此操作,则对于键name的不同值,应考虑一次性构造哈希值以加快查找速度。

SUPPLIERS = [
  { name: "FunePlus", advitam_grade: 3, works: [ { type: "embalming", price: 350 }, 
    { type: "transport_before_casketing", price: 450} ]},
  { name: "FuneTop",                    works: [ { type: "graving", price: 10 } ]},
  { name: "FuneTruc", advitam_grade: 5, works: [ { type: "embalming", price: 750 }]},
  { name: "FuneCorp", advitam_grade: 2, works: [ { type: "digging", price: 350 }]}
]

class SelectSupplier
  @supplier_index = SUPPLIERS.each_with_index.with_object({}) { |(g,i),h| h[g[:name]] = i }
  def self.global_grade(name)
    SUPPLIERS[@supplier_index[name]]
  end
end

SelectSupplier.global_grade("FunePlus")
  #=> {:name=>"FunePlus", :advitam_grade=>3, :works=>[{:type=>"embalming", :price=>350},
  #     {:type=>"transport_before_casketing", :price=>450}]}

哈希@supplier_index等于以下内容。

SelectSupplier.instance_variable_get(:@supplier_index)
  #=> {"FunePlus"=>0, "FuneTop"=>1, "FuneTruc"=>2, "FuneCorp"=>3}

请注意,我本可以用等于@supplier_index元素(哈希)的值构造SUPPLIERS,但这会增加内存需求(当然,这可能不是问题)。