I'm looking for some help on how to take an attribute and process it through a method to return something different. But I've never done this before and I' not sure where to start. I thought trying to change a name:string attribute from "George Washington" or "John Quincy Adams" into first names only "George" and "John".
I thought maybe a helper method would be best, such as
users_helper.rb
def first_name
end
and then call @user.name.first_name, would this be initially how it would work? Can someone explain where I'd go next to be able to pass @user.name into the method? I've seen things like this but don't quite understand it the parenthesis...
def first_name(name)
puts name
end
Could someone breakdown how rails/ruby does this type of thing? Thanks a lot!
In case you are looking to split only once and provide both parts this one liner will work:
Makes the last word the last name and everything else the first name. So if there is a prefix, "Dr.", or a middle name that will be included with the first name. Obviously for last names that have separate words, "Charles de Gaulle" it won't work but handling that is much harder (if not impossible).
The parentheses (which are optional) enclose the parameter list.
This assumes the parameter is not nil.
But this is not a string method, as your assumption is now:
Instead:
This could be wrapped up in the model class itself:
The extra code checks to see if the name is nil or whitespace (
blank?
comes from Rails). If it is, it returns an empty string. If it isn't, it splits it on spaces and returns the first item in the resulting array.making it simple
Thanks
Output:
Some people have more than two names, such as "John Clark Smith". You can choose to treat them as:
(1) first_name: "John", last_name: "Smith"
(2) first_name: "John Clark", last_name: "Smith"
(3) first_name: "John", last_name: "Clark Smith"
The above examples assume that if the name contains less than 2 words then it is a first name.
Use Ruby's
Array#pop
For my needs I needed to take full names that had 1, 2, 3 or more "names" in them, like "AUSTIN" or "AUSTIN J GILLEY".
The Helper Method
Using It
And you can easily assign the
first_name
andlast_name
with:You can modify from there based on what you need or want to do with it.