1

The following code won't change the variable:

@my_var = ''
@my_var ||= 'This is a non-empty string'

Is there any nice/clean way to do this so that empty strings are overwritten?

5
  • Here, @my_var in not null. So, you've to do something like this: @my_var = 'This is a non-empty string' if @my_var.empty? or @my_var = 'This is a non-empty string' unless @my_var.present? Commented Oct 27, 2020 at 3:54
  • monkey patching can help you, stackoverflow.com/questions/647370/… Commented Oct 27, 2020 at 3:56
  • 3
    monkey-patching may cause you grief. Commented Oct 27, 2020 at 3:58
  • Other way you can set value as nil instead of ''(blank string) like => @my_var = ''.presence @my_var ||= 'This is a non-empty string' Commented Oct 27, 2020 at 3:59
  • If @my_var is undefined / not set, you should avoid empty string and just use nil instead. Commented Oct 27, 2020 at 7:36

2 Answers 2

12

you can try like this:

@my_var = ''
@my_var = @my_var.presence || 'This is a non-empty string'

Thanks :-)

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know that, great tip!
1

in this case, i would just check the length of this string:

@my_var = ''
@my_var = 'This is a non-empty string' if @my_var.length == 0
=> "This is a non-empty string"

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.