A Neat Trick for Splitting Strings
You probably needed to split a full name into first and last name at some point.
How would you split the string Ayrton Senna da Silva into Ayrton as the first name and Senna da Silva as the last name?
What if the name contains inconsistent amounts of whitespace in between the words? Eg: Ayrton Senna da Silva.
"Ayrton Senna da Silva".split(" ")
# => ["Ayrton", "Senna", "da", "Silva"]Splitting by space is a good start, but it doesn't finish the job.
Solution
I learned recently we can pass a second argument to split specifying the maximum number of splits:
"Ayrton Senna da Silva".split(" ", 2)
# => ["Ayrton", "Senna da Silva"]That almost worked, but we still have an extra space in the last name.
By combining it with squish we can get the desired result in a clean way:
"Ayrton Senna da Silva".squish.split(" ", 2)
# => ["Ayrton", "Senna da Silva"]That's it.
Written on January 15, 2026