Reputation: 9773
I want to generate full names from title
, first_name
, middle_name
, and last_name
. e.g. Mr Billy Bob Thornton. But the title
and middle_name
are optional and I don't want to get any leading or double spaces. I've come up with lots of ways of doing them but none of them seem really elegant. Here are my techniques so far
full_name = "#{title} #{first_name} #{middle_name} #{last_name}"
#FAIL. Leading and double spaces result
full_name = "#{title} #{first_name} #{middle_name} #{last_name}".gsub(/^ /,'').gsub(/ /,' ')
#Works but all that regex tacked on the end is very ugly
full_name = "#{title}#{title.nil? || title.empty? ? '' : ' '}#{first_name} #{middle_name}#{middle_name.nil? || middle_name.empty? ? '' : ' '}#{last_name}"
#Works but goes on forever
I'll be using rails so can reduce my .nil? || .empty?
to .blank?
to make the last one a little more concise but I can't help but think that there's a nicer way.
Upvotes: 1
Views: 325
Reputation: 434795
You're using Rails so you have access to String#squish
:
squish()
Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.
So you could do this:
name = "#{title} #{first_name} #{middle_name} #{last_name}".squish
Upvotes: 9
Reputation: 88428
Check out Ruby's String#squeeze and String#strip
>> title=""
=> ""
>> first_name="Alice"
=> "Alice"
>> middle_name=""
=> ""
>> last_name=""
=> ""
>> full_name = "#{title} #{first_name} #{middle_name} #{last_name}".squeeze(" ").strip
=> "Alice"
>> last_name="Wu"
=> "Wu"
>> full_name = "#{title} #{first_name} #{middle_name} #{last_name}".squeeze(" ").strip
=> "Alice Wu"
Generalizing to a function should be pretty easy.
Upvotes: 2
Reputation: 160893
[title, first_name, middle_name, last_name].select({|v| v.present?}).join(' ')
Upvotes: 0
Reputation: 15010
Would you be looking for something like this ?
[title, first_name, middle_name, last_name].compact.reject(&:empty?).join(' ')
with Rails
[title, first_name, middle_name, last_name].select(&:present?).join(' ')
Upvotes: 2