Rails,如何循环散列数组或只散列散列

问题描述 投票:0回答:2

我正在连接到一个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);

当我输入放extra.inspect;我得到["id", "640079840000100800"]。所以为了使它工作,我应该通过extra[1]来获取身份证号码。

但我无法预测哈希数组或哈希值。有没有简单的方法来解决这个问题,无论是散列数组还是散列数?

ruby-on-rails arrays ruby hash
2个回答
3
投票

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

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

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

[*[input]].flatten

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

如果您没有使用Rails帮助过敏,请参阅下面@Stefan的宝贵评论。


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
© www.soinside.com 2019 - 2024. All rights reserved.