Concatenate to nil should return nil in Ruby

Viewed 198

I need to produce a string surrounded by parenthesis but only if its value is not empty. Currently I'm using something similar to:

[5] pry(main)> a = nil
=> nil
[6] pry(main)> a.nil? ? '' : "(#{a})"
=> ""
[7] pry(main)> a = "world"
=> "world"
[8] pry(main)> a.nil? ? '' : "(#{a})"
=> "(world)"

But I consider it to be repetitive. Is there a simpler way?

2 Answers

You could just write a method that does this:

def bracketize(str)
  return '' unless (str)
  "(#{str})"
end

As that makes it clear what you're doing and you don't have to stamp this code all over the place.

Just put your code in a method:

def parentheses(a=nil)
  a.nil? ? '' : "(#{a})"  
end 
Related