Rails,如何循环哈希数组或仅哈希

时间:2017-12-19 11:33:25

标签: ruby-on-rails arrays ruby hash

我正在连接到API,我得到哈希数组或数据只有1个哈希值。所以当数据以哈希数组出现时;

"extras"=>{"extra"=>[{"id"=>"529216700000100800", "name"=>"Transfer Trogir - Dubrovnik (8 persons max)", "price"=>"290.0", "currency"=>"EUR", "timeunit"=>"0", "customquantity"=>"0", "validdatefrom"=>"1970-01-01", "validdateto"=>"2119-07-20", "sailingdatefrom"=>"1970-01-01", "sailingdateto"=>"2119-07-20", "obligatory"=>"0", "perperson"=>"0", "includedinbaseprice"=>"0", "payableoninvoice"=>"1", "availableinbase"=>"-1", "includesdepositwaiver"=>"0", "includedoptions"=>""}, {"id"=>"528978430000100800", "name"=>"Gennaker + extra deposit (HR)", "price"=>"150.0", "currency"=>"EUR", "timeunit"=>"604800000", "customquantity"=>"0", "validdatefrom"=>"1970-01-01", "validdateto"=>"2119-07-19", "sailingdatefrom"=>"1970-01-01", "sailingdateto"=>"2119-07-19", "obligatory"=>"0", "perperson"=>"0", "includedinbaseprice"=>"0", "payableoninvoice"=>"1", "availableinbase"=>"-1", "includesdepositwaiver"=>"0", "includedoptions"=>""}]

我循环遍历数组以获取值;

b["extras"]["extra"].each do |extra|
  puts extra["id"]
  puts extra["name"]
end

但是这不是阵列;只有1个哈希,然后这不起作用,添加每个循环使它成为数组但不是哈希数组;

"extras"=>{"extra"=>{"id"=>"640079840000100800", "name"=>"Comfort package (GRE)", "price"=>"235.0", "currency"=>"EUR", "timeunit"=>"0", "customquantity"=>"0", "validdatefrom"=>"1970-01-01", "validdateto"=>"2120-03-25", "sailingdatefrom"=>"2015-01-01", "sailingdateto"=>"2120-03-25", "obligatory"=>"1", "perperson"=>"0", "includedinbaseprice"=>"0", "payableoninvoice"=>"1", "availableinbase"=>"-1", "includesdepositwaiver"=>"0", "includedoptions"=>""}}


b["extras"]["extra"].each do |extra|
  puts extra["id"]
  puts extra["name"]
end

这一次,它给出了错误TypeError(没有将String隐式转换为Integer);

当我键入puts extra.inspect;我得到["id", "640079840000100800"]。为了使其工作,我应该通过extra[1]来获取ID号。

但我无法预测哈希数组或仅哈希数。有没有简单的方法可以解决这个问题,它可以使用散列数组还是哈希值?

2 个答案:

答案 0 :(得分:3)

天真的解决方案:可以预先检查对象的类型:

case b["extras"]["extra"]
when Array
    # handle array
when Hash
    # handle hash
end

正确的解决方案:无论发生什么,都会产生一系列哈希值。

[*[input]].flatten

并与具有至少一个哈希元素(带each的数组一样处理它。)

如果你没有使用Rails助手过敏,请参考@Stefan的宝贵评论。

答案 1 :(得分:2)

您可以尝试使用Object#kind_of?来确定它是Array还是Hash实例。

if b["extras"]["extra"].kind_of? Array
    # handle array
elsif b["extras"]["extra"].kind_of? Hash
    # handle hash
end