开发者

Help me get rid of the space " "

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜