2

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

3
  • If you are using a library, then make that clear. Commented Oct 10, 2017 at 9:47
  • @sawa: to his credit, it's not always obvious which things are rails and not standard ruby. You can't expect him to add tags for all the gems in his gemfile. Commented Oct 10, 2017 at 9:48
  • @sawa Yeah I am using Rails but the question doesn't imply that I need a Rails method to do what I want, if there is a native Ruby one. I just happened to use a rails method in my example. I'll update the question anyway. Commented Oct 10, 2017 at 9:51

2 Answers 2

11

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
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

what about .compact.first ?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.