轨道,如何循环一系列哈希或只有哈希



我正在连接到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"=>""}]

i im循环通过数组循环以将值作为;

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(不隐含字符串转换为整数);

当我输入时,请put extra.inspect;我得到["id", "640079840000100800"]。因此,为了使它起作用,我应该通过extra[1]获取ID号。

,但我无法预测哈希的数组或仅哈希。是否有任何简单的方法可以解决此问题,以便有效的哈希或只是哈希?

幼稚的解决方案:一个人可能会检查对象的类型:

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

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

[*[input]].flatten

和与具有至少一个哈希元素的数组(使用each。)

进行处理。

,如果您没有使用Rails Helpers的过敏,请参考以下@stefan的宝贵评论。

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

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

最新更新