Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Full name in Ruby on Rails

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
like image 566
Santi Avatar asked Jan 21 '16 10:01

Santi


2 Answers

You can try this:

def name
  [first_name, middle_name, last_name].select(&:present?).join(' ').titleize
end
like image 193
Hieu Pham Avatar answered Sep 21 '22 20:09

Hieu Pham


Use this instead

def name
  [first_name, middle_name, last_name].reject(&:blank?).join(' ').titleize
end
like image 23
toomanyredirects Avatar answered Sep 23 '22 20:09

toomanyredirects