开发者

Help me get rid of the space " "

开发者 https://www.devze.com 2023-02-27 01:59 出处:网络
def name @name || \"#{self.first_name} #{self.last_name}\" end If first name and last name are both empty name is a 开发者_Python百科space \" \". How do I rewrite the right-hand side so it\'s an emp
def name
  @name || "#{self.first_name} #{self.last_name}"
end

If first name and last name are both empty name is a 开发者_Python百科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).

0

精彩评论

暂无评论...
验证码 换一张
取 消