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).
精彩评论