1

I often encounter the following case: I want to set a variable unless it is present. Of course this can be easily done by doing so:

var1 = ""
var1 = "dhiughr" unless var1.present?

If it was nil this could be done with a simple ||= operator, but since an empty string is not nil it won't work. I have tried reading on Ruby's or operator, which theoretically should work:

var1 = "" or "dhiughr"

but it doesn't. I expect the second string (right from the operator) to be chosen when the first isn't present?

What am I doing wrong?

2
  • Why in your opinion "or operator theoretically should work"? Commented Feb 18, 2014 at 12:29
  • Is there a way to get a one liner for that expression? Commented Feb 18, 2014 at 12:30

2 Answers 2

8

You can do it this way, using Object#presence method (which comes as extension from active_support library):

var1 = var1.presence || 'dhiughr'

It works as you expect:

var1 = ''
var1 = var1.presence || 'dhiughr'
var1
# => "dhiughr"
var1 = 'foo'
var1 = var1.presence || 'dhiughr'
var1
# => "foo"
Sign up to request clarification or add additional context in comments.

3 Comments

Why wouldn't he use just ||= ?
@scaryguy read the question carefully and you'll get the answer.
I have no idea. I got 2 down votes for my answer and I deleted it.. People doesn't like others talking about their own vote status I guess.
1

In ruby empty string is truthy value. See What's truthy and falsey in Ruby?

Ruby:

var1 = ''
var1 = var1.to_s == '' ? 'dhiughr' : var1

With rails:

var1 = ''
var1 = var1.blank? ? 'dhiughr' : var1

Comments

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.