replace fields in a string with data


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. info = "Hello World %firstname% %lastname% today is %date% ."
  2. fields = { 'firstname' => "Jamie", 'lastname' => "Allison"}
  3.  
  4. info.gsub!(/(%.*?%)/) do |m|
  5. m.gsub!(/%/, '')
  6. fields[m]
  7. end
  8.  
  9. puts info
  10. # >> Hello World Jamie Allison today is .
  11. # Note if field is not in fields array, it is simply replaced with an empty
  12. # string, like the %date% field above

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.