简体   繁体   English

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

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

Being the xml result of a HttParty request 作为HttParty请求的xml结果

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

Some have entered their weight and height, some others only their height 有些输入了他们的体重和身高,有些输入了他们的身高

So wen I do 所以我做

entries.each do |item|

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

It breaks when it finds the first person with no registered weight. 找到第一个没有注册体重的人时,它会中断。 I have tried using .nil? 我尝试使用.nil? with no luck. 没有运气。 How can I recognize non existent fields? 如何识别不存在的字段?

I imagine item is an hash. 我想象项目是一个哈希。 So there are things you can do 所以有些事情你可以做

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

or 要么

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

I suggest you to study Ruby hashes 我建议你学习Ruby哈希

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM