Maurice Kroon
Maurice Kroon

Reputation: 959

if variable empty do default

Currently, I've got this:

self.profile_pic = user_info['image']
self.birthday = user_extra['birthday']
self.city = user_extra['location']['name']

Sometimes the user_extra or user_info var is blank. I would like to have a default value then. How to do this?

Thanks in advance,

Maurice

Upvotes: 0

Views: 1392

Answers (1)

Christopher WJ Rueber
Christopher WJ Rueber

Reputation: 2161

It really depends on how specific you want to get. Is it blank or nil? Because there's a big difference there. In Ruby, a blank String is not evaluated to false. Assuming that the specific hash of that variable is nil, this would work...

self.profile_pic = user_info['image'] || "default"
self.birthday = user_extra['birthday'] || "default"
self.city = user_extra['location']['name'] || "default"

Or you could have it be a more general check to make sure the variable isn't nil itself, using the ternary operator...

self.profile_pic = user_info ? user_info['image'] : "default"
self.birthday = user_extra ? user_extra['birthday'] : "default"
self.city = user_extra ? user_extra['location']['name'] : "default"

Or, if it actually is blank and not nil, something more like this...

self.profile_pic = user_info.empty? ? "default" : user_info['image']
self.birthday = user_extra.empty? ? "default" : user_extra['birthday']
self.city = user_extra.empty? ? "default" : user_extra['location']['name']

It depends on the exact conditions you have, and how far down the rabbit hole you want to go. :) Hope that helps!

Upvotes: 3

Related Questions