Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
@my_var
@my_var = 'This is a non-empty string' if @my_var.empty?
@my_var = 'This is a non-empty string' unless @my_var.present?
nil
''
@my_var = ''.presence @my_var ||= 'This is a non-empty string'
you can try like this:
@my_var = '' @my_var = @my_var.presence || 'This is a non-empty string'
Thanks :-)
Add a comment
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"
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
@my_varin 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?nilinstead of''(blank string) like =>@my_var = ''.presence @my_var ||= 'This is a non-empty string'@my_varis undefined / not set, you should avoid empty string and just usenilinstead.