tags:

views:

63

answers:

3

What's the best way of doing this:

mail = "[email protected]"
mail2 = mail.do_magic
# puts mail2 will return "[email protected]"

I'm thinking regex of course, but is there another cool way? If not, how should I do it using regexp?

+3  A: 

Not sure I completely understand what you're asking, but couldn't you use regex like this?

irb(main):001:0> email = "[email protected]"
=> "[email protected]"
irb(main):002:0> email.gsub(/@[\w.]+/, '@something.com')
=> "[email protected]"

Let me know I've missed something or if I'm not understanding the question correctly.

jerhinesmith
I totally forgot that you could use regex with gsub... I officially lost my mind. Thanks a lot!
marcgg
Glad I could help! Keep in mind I threw that regex together fairly quickly, so there might be a better expression for doing the replace.
jerhinesmith
There are tons of validation on the email before getting to this action, so just catching the @ will work just fine, but good point for a future reader ^^
marcgg
+1  A: 

You can use regexps in strings indexes too:

email = "[email protected]"
replace = "foobar.invalid"
email[/@.*/] = "@#{replace}"

If you don't want to modify email:

(new = email.dup)[/@.*/] = "@#{replace}"
p [email,new]  # => ["[email protected]", "[email protected]"]
glenn jackman
A: 

Another approach, avoiding regular expressions, is to split and join

new = [email.split('@').first, "foobar.invalid"].join('@')
glenn jackman