如何检查 Httparty 和 Ruby 中不存在的 fieldw?

How to check non-existent fieldw in Httparty and Ruby?

作为 HttParty 请求的xml结果

<people>
                <person>
                    <height>192</height>
                    <weight>80</weight>
                </person>
                <person>
                    <height>180</height>
                </person>
</people>

有的输入了体重和身高,有的只输入了身高

我也是

entries.each do |item|

puts item["person"]["height"]
puts item["person"]["weight"]
end

当它发现第一个没有登记体重的人时,它就会崩溃。我曾尝试使用 .nil? 但没有成功。我如何识别不存在的字段?

我想 item 是一个散列。所以有些事情你可以做

person = item["person"]
if person.key?("weight")
  puts person["weight"] 
else
  puts "no weight"
end

person = item["person"]
puts person.fetch("weight", "no weight")

我建议你学习Ruby哈希