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!
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.