def name
@name || "#{self.first_name} #{self.last_name}"
end
If first name and last name are both empty name is a space " ". How do I rewrite the right-hand side so it's an empty string "" instead of a space " "?
You can just add .strip at the end:
>> ln = 'last' #=> "last"
>> fn = 'first' #=> "first"
>> "#{fn} #{ln}".strip #=> "first last"
>> fn = nil #=> nil
>> ln = nil #=> nil
>> "#{fn} #{ln}".strip #=> ""
def name
@name ||= [first_name, last_name].compact * " "
end
This solution has the advantage of not including a trailing or leading space when either name is nil, and it works in the general case (i.e. for any number of strings).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With