2

I want to convert a string with an email address into ASCII characters for placing in a HTML document. What's the easiest way to do this?

I keep getting an array back in my HTML document with the characters using this code in my model:

def ascii_email
  self.email.each_byte do |e|
    "&#",  e, ";"
  end
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Josh Brown
  • 861
  • 2
  • 10
  • 19
  • Is this a valid ruby code? I could not get your question. – sawa May 10 '11 at 00:58
  • This seems to be very closely related to this other question: http://stackoverflow.com/questions/1600526/how-to-encode-decode-html-entities-in-ruby – buruzaemon May 10 '11 at 00:59

1 Answers1

4

You're iterating over the characters in the email address without actually using them, so that's not going to be what you want.

 def ascii_email
   self.email.bytes.collect do |e|
      "&\##{e};"
   end.join('')
 end

There's an important yet subtle difference between an iterator that simply goes through the elements and one that returns the transformed results. Also missing in your snippet was something that turned the transformed array back into a string.

tadman
  • 208,517
  • 23
  • 234
  • 262