jasonng
jasonng

Reputation: 107

Finding and replacing strings

The app that I'm building allows users to store first and last names of contacts. First names are mandatory, but, last names aren't. In some cases they exist and in some cases they don't.

I tried using the following logic to replace LNAME with the last name of the contact.

def replace_names
   self.message.gsub! 'LNAME', contact.last_name
   self.message.gsub! 'FNAME', contact.first_name
   #METHOD 2    
   #h = {"FNAME" => contact.first_name,"LNAME" => contact.last_name}
   #self.message.gsub!(/\w+/) { |m| h.fetch(m,m)}
   #METHOD 3
   #self.message.gsub!(/[FNAMELNAME]/, 'FNAME' => 1, 'LNAME' => 2)
end

When both first and last names are present, the logic (uncommented one) works perfectly fine. However, when there is no last name, the results are all over the place. In some places the LNAME is displayed as LNAME and in some places it isn't shown.

I went through a few other SO solutions and they didn't work as expected when the last name is absent. I would really appreciate a suggestion.

Upvotes: 0

Views: 67

Answers (1)

Vu Minh Tan
Vu Minh Tan

Reputation: 526

When contact.last_name is not present, you should replace 'LNAME' with an empty string

   self.message.gsub! 'LNAME', contact.last_name || ''

Upvotes: 1

Related Questions