gpt4 book ai didi

ruby - 如何避免多次 'nil' 检查?

转载 作者:太空宇宙 更新时间:2023-11-03 17:55:48 24 4
gpt4 key购买 nike

我正在解析 JSON 数据,并且在很多数据上我必须调用一些方法。有时数据为“nil”,如果我不检查 nil,则在调用方法时会抛出错误。

我现在正在做的是创建一个变量,检查是否为 nil,然后在对它调用一个方法后最终将它分配给我的散列。这是一个例子:

lat = event['location']['lat']
lng = event['location']['lng']
popularity = event['popularity']

ar_show.lat = lat.round(4) if lat
ar_show.lng = lng.round(4) if lng
ar_show.popularity = popularity.round(4) if popularity

是否有“更好”或更优雅的方式来做到这一点?目前我这样做的方式似乎非常多余,创建一个额外的变量只是为了避免在 nil 上调用方法。我可以这样做:

ar_show.lat = event['location']['lat'].round(4) if event['location']['lat']

但更糟的是!

也许对我来说它看起来很奇怪的原因是我花了很多时间写 Objective-C,我可以懒惰地使用它,因为发送消息到 'nil' 很好,你可以避免很多 nil检查,但也因此有时也会把自己搞砸。


更新:

我刚刚在一个语句中找到了一种使用 to_f 强制执行此操作的方法:

ar_show.lat = event['location']['lat'].to_f.round(4)

to_f 在 nil 上将使其成为 0.0,处理 nil 情况,并避免额外的变量或语句。我只是想知道在我将它输入我的代码之前这是否有缺点?

最佳答案

您可以使用默认值:

lat = event['location']['lat'] || 0
ar_show.lat = lat.round(4)

在某些时候您必须处理 nil 情况,为什么不在分配时处理它呢?

关于ruby - 如何避免多次 'nil' 检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com