Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me get rid of the space " "

Tags:

ruby

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 " "?

like image 331
Aen Tan Avatar asked Dec 07 '25 10:12

Aen Tan


2 Answers

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 #=> ""
like image 115
Michael Kohl Avatar answered Dec 11 '25 03:12

Michael Kohl


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).

like image 38
molf Avatar answered Dec 11 '25 01:12

molf