我有两个哈希如下:
A:
{"items"=>[
{"id"=>"1582047441225902782_5735285038", "location"=>{"name"=>"city, country"}},
{"id"=>"1582045444762412016_5735285038", "location"=>{"name"=>"city, country"}},
{"id"=>"1579295851704320004_5735285038", "location"=>{"name"=>"city, country"}}
]
}
B:
{"items"=>[
{"id"=>"1291968139634730329_3268566686", "location"=>nil},
{"id"=>"1289715984018418358_3268566686", "location"=>nil},
{"id"=>"1265437960134352110_3268566686", "location"=>nil},
{"id"=>"1265436628937759921_3268566686", "location"=>nil},
{"id"=>"1265435354792090734_3268566686", "location"=>nil},
{"id"=>"1263837986099453523_3268566686", "location"=>nil},
{"id"=>"1263836777863077412_3268566686", "location"=>nil},
{"id"=>"1263835770617748979_3268566686", "location"=>nil},
{"id"=>"1263058120273977093_3268566686", "location"=>nil},
{"id"=>"1263049902374149585_3268566686", "location"=>nil}
]
}
如果我的所有位置都是零,我需要看看,即使单个位置都没有值,所以数组应该返回false。
如果单个元素具有位置值,则它应该返回true,这意味着所有位置都是零,但很少或者一个也有值。
我想尝试:
ary['items'].map {|e| puts e['location']['name'].nil?}
但它说:
NoMethodError (undefined method `[]' for nil:NilClass):
答案 0 :(得分:3)
只需使用all?
方法。
ary["items"].all? { |item| item["location"].nil? }
答案 1 :(得分:2)
使用单行检查至少一个位置是否nil
:
ary['items'].any? { |item| !item['location'].nil? }