There is a way that does this for you:
def show @city = @user.city.present? end
present? method test present? for not- nil plus has content. Blank lines, lines consisting of spaces or tabs are considered absent.
Since this template is so common, thereβs even a shortcut in ActiveRecord:
def show @city = @user.city? end
This is roughly equivalent.
As a side note, vs nil testing is almost always redundant. In Ruby, there are only two logically false values: nil and false . If it is not possible for the variable to be literal false , this would be sufficient:
if (variable)
This is preferable to the usual if (!variable.nil?) Or if (variable != nil) stuff, which sometimes appears. Ruby is leaning toward a more reductionist type of expression.
One of the reasons you want to compare vs. nil , is if you have a tri-state variable that can be true , false or nil , and you need to distinguish between the last two states.
tadman Apr 09 '14 at 17:44 2014-04-09 17:44
source share