ivanibash
ivanibash

Reputation: 1491

Conditional assignment with empty strings

I love conditional assignment syntax in Ruby and use it all the time:

x = this_var || that_var

Right now I am working with several APIs, which return empty strings for non-existing values. Since empty string evaluates to true in Ruby I can no longer use the syntax above to set default values. It gets worse when I have several "levels" of defaults, e.g. "if this var doesn't exist set it to that var, if that doesn't exist too, set it to yet another var". So I end up doing this:

x = if this_var.present?
       this_var
    elsif that_var.present?
       that_var
    else
       last_resort
    end

The .present? method helps but not much. How would I write something like this in a more concise way?

I am using Rails 4 so Rails methods are welcome as an answer :)

Thanks

Upvotes: 2

Views: 1523

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

This is where you use present?'s brother, presence (assuming you use rails or at least active support).

x = this_var.presence || that_var.presence || last_resort

Upvotes: 11

sawa
sawa

Reputation: 168101

x = [this_var, that_var, last_resort].find(&:present?)

Upvotes: 5

Related Questions