Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails using || to determine value, using an empty string instead of a nil value

I usually do

 value = input || "default"

so if input = nil

 value = "default"

But how can I do this so instead of nil It also counts an empty string '' as nil

I want so that if I do

input = ''
value = input || "default"
=> "default"

Is there a simple elegant way to do this without if?

like image 729
Tarang Avatar asked Sep 06 '25 03:09

Tarang


2 Answers

Rails adds presence method to all object that does exactly what you want

input = ''
value = input.presence || "default"
=> "default"

input = 'value'
value = input.presence || "default"
=> "value"

input = nil
value = input.presence || "default"
=> "default"
like image 118
dimuch Avatar answered Sep 07 '25 21:09

dimuch


I usually do in this way:

value = input.blank? ? "default" : input

In response to the case that input might not be defined, you may guard it by:

value = input || (input.blank? ? "default" : input)
# I just tried that the parentheses are required, or else its return is incorrect

For pure ruby (not depending on Rails), you may use empty? like this:

value = input || (input.empty? ? "default" : input)

or like this (thanks @substantial for providing this):

value = (input ||= "").empty? ? "default" : input
like image 33
PeterWong Avatar answered Sep 07 '25 20:09

PeterWong