0xSina
0xSina

Reputation: 21553

How do I avoid many 'nil' checks?

I am parsing JSON data and on a lot of data I have to call some methods. Sometimes the data is 'nil' and, if I don't check for nil, it throws an error if a method is called.

What I am doing right now is create a variable, check for nil, and then assign it finally to my hash after calling a method on it. Here's an example:

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      

Is there a 'better' or more elegant way to do this? It seems very redundant at the moment the way I am doing it, creating an extra variable just for the sake of avoiding calling a method on nil. I can do this:

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

but that's even worse!

Maybe the reason why it seems weird to me is become I have spent a lot of time writing Objective-C and I can be lazy with it because it's fine to send messages to 'nil' and you can avoid a lot of nil checking, but also because of this at times screw yourself over too.


UPDATE:

I just found a way to do this in one statement using to_f coercion:

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

to_f on a nil will make it 0.0, handling the nil case, and avoiding an extra variable or statement. I just wonder if there's a downside to this before I enter it into my code?

Upvotes: 1

Views: 317

Answers (2)

0xSina
0xSina

Reputation: 21553

I found a way to do this in one statement using to_f to coerce nil:

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

to_f on a nil will make it 0.0 handling the nil case, avoiding an extra variable or statement.

Got the answer from this video.

Upvotes: 1

Femaref
Femaref

Reputation: 61437

You could use a default value:

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

You'll have to handle the nil case at some point, why not handle it while assigning it?

Upvotes: 3

Related Questions