Getting information from users is a common task that we have to deal with in building an application. This typically happens either in creating a user account, commerce orders, or any other time when the application has to ask “who are you?”. Often times we’ll create a field for both a firstname and a lastname allowing the user to separate their names to make it easier for us (the application developer) to display either/or both. In this post, I’m going to talk about how we can format full names given to the application by the user without necessarily worrying about creating two textfields. Of course, you would use this code in the methods within a Rails app.
So let’s say I have a variable for creative purposes, I’ll call it ‘name’ and ‘name’ has a value.
name = “James Earl Jones”
And I want to only display the first and last name of my ‘name’ value I could do this:
names = name.split
firstname = names.first
lastname = names.last
Now this splits the three words in ‘name’ into an array. I then set firstname as the first item from the array, and set lastname as the last item from the array.
Running:
p “#{firstname} #{lastname}”
Would then output:
“James Jones”
How about we do another common formatting task we can to show the last name first separated with a comma the rest of the name, we could do this:
names = name.split
lastname = names.pop
firstname_remaining = names.join(‘ ‘)
Here we split the name up again, put then ran the pop method which pulls the last time of the array out of the array and then returns it. This would leave only the remaining name left to work with as the firstname_remaining variable. I them join the rest of the array with spaces for the firstname_remaining (which would include the first name and any remain name information like a middle name).
Running:
p “#{lastname}, #{firstname_remaining}”
Would then output:
“Jones, James Earl”
Lastly, a common thing I’ve been seeing lately is the usage of the last initial when showing a user’s name. We could do something like this:
names = name.split
firstname = names.first
lastinitial = names.last[0,1]
Here I’m introducing some trimming for the lastinitial variable. You see this with a bracket and two numbers. The first number is the offset in the string that I’m trimming (zero is the first letter is a string), the next number is how many characters I’m showing from that offset.
Running:
p “#{firstname} #{lastinitial}.”
Would then output:
“James J.”
So that’s it for now. Of course you might think about adapting this to users that will have items at the end of their name like “Jr.” – this can sometimes just be solved using a drop-down. I’m hoping that perhaps I have introduced you to some things in Ruby that you might have been previously unaware of. Until next time.