【问题标题】:How do I avoid many 'nil' checks?如何避免许多“零”检查?
【发布时间】:2012-12-11 00:52:45
【问题描述】:

我正在解析 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 coercion 的语句中找到了一种方法:

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

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

【问题讨论】:

  • 我认为to_f 技巧(或相关的to_ito_a 技巧)本身没有任何问题。最大的问题是它们可以隐藏表示更深层次问题的意外值(例如nils 或不应该存在的字符串)。所以通常的“明智地使用你的工具,不要因为混乱而壁纸”的建议适用。

标签: ruby


【解决方案1】:

我在一个使用to_f 强制为零的语句中找到了一种方法:

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

to_f 在 nil 上将使其 0.0 处理 nil 情况,避免额外的变量或语句。

this视频中得到答案。

【讨论】:

    【解决方案2】:

    您可以使用默认值:

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

    您必须在某个时候处理nil 案例,为什么不在分配时处理它?

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多