Sometimes we need to split a full name into first name and last name parts. In Ruby String#split is the default thinking. If the name is just two parts, like "John Doe" it'd work like breeze.

But the problem arises when it has more works in it, ike "John M Doe". I would want "John M" in first part and "Doe" as last name.

In this case a simple split would fail. After some digging I found String#rpartition, it worked smoothly. Here is the snippet I used:

def parse_full_name(name)
  names = name.to_s.rpartition(' ').reject(&:blank?)
  first_name, last_name = name, nil
  last_name = names.last if names.size > 1
  first_name = names[0..-2].join(' ') if names.size > 1
  [first_name, last_name]
end

If you've any better solution, please let us know in the comments bellow. :)




What's on your mind?