我正在解析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)
nil上的 to_f
会使它成为0.0
,处理nil情况,并避免使用额外的变量或语句。我只是想知道在我输入代码之前是否存在不足之处?
答案 0 :(得分:3)
您可以使用默认值:
lat = event['location']['lat'] || 0
ar_show.lat = lat.round(4)
您必须在某个时候处理nil
案件,为什么不在分配时处理它?</ p>
答案 1 :(得分:1)
我在一个声明中找到了一种方法,使用to_f
来强制执行nil:
ar_show.lat = event['location']['lat'].to_f.round(4)
to_f
在nil上会使0.0处理nil情况,避免使用额外的变量或语句。
从this视频得到答案。