I need to solve a simple issue in Ruby, but want to do it in a smart way. I have a function:
def fullname
first + " " + mi + last
end
That will crash if one or more of the variables is nil, let's say mi for this example since it's in the center.
Error:
can't convert nil into String
If I change the function to:
def fullname
first + " " + mi.to_s + last
end
or
def fullname
first + " " + (mi || "") + last
end
It will fix it. Now I want to add an additional space after the mi (middle initial) if it is present and I'm stumped for some silly reason. What would be the cleanest way to do something like this, as I will be having to do it a lot and sometimes adding say a comma.
Example of that need:
def fullname
first + " " + (mi || "") + last + suffix
# want a ", " afer the last name if there is a suffix
end