Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 977
ivanibash Avatar asked Sep 13 '26 13:09

ivanibash


1 Answers

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
like image 149
Sergio Tulentsev Avatar answered Sep 15 '26 07:09

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!