Reputation: 631
In below example, the middle_name
is optional. Any name without middle_name
it takes an extra blank space. Please anyone make correction following method.
def name
"#{first_name} #{middle_name} #{last_name}".titleize
end
Upvotes: 5
Views: 2408
Reputation: 126
This guards and formats: (e.g.) => Scott, Michael G
def full_name
return if last_name.blank? && first_name.blank?
["#{last_name}, #{first_name}", middle_initial, suffix].select(&:present?).join(' ').titleize
end
Upvotes: 0
Reputation: 2364
Contracting the middle names:
def formatted_name(full_name)
parts = full_name.split
name = parts.first
name += " #{parts[1][0,1].upcase}. " if parts.length > 2
name += " #{parts[2][0,1].upcase}. " if parts.length > 3
name += parts.last
end
puts formatted_name("Bob Alan Faria Stwart") => "Bob A. F. Stwart"
Upvotes: -1
Reputation: 2424
def name
"#{first_name} #{middle_name}#{" " if middle_name.present?}#{last_name}".titleize
end
Upvotes: 0
Reputation: 2002
Use this instead
def name
[first_name, middle_name, last_name].reject(&:blank?).join(' ').titleize
end
Upvotes: 5
Reputation: 6692
You can try this:
def name
[first_name, middle_name, last_name].select(&:present?).join(' ').titleize
end
Upvotes: 14