What's the best way of doing this:
mail = "bob@something.com"
mail2 = mail.do_magic
# puts mail2 will return "bob@anotherwebsite.com"
I'm thinking regex of course, but is there another cool way? If not, how should I do it using regexp?
From stackoverflow
-
Not sure I completely understand what you're asking, but couldn't you use regex like this?
irb(main):001:0> email = "bob@example.com" => "bob@example.com" irb(main):002:0> email.gsub(/@[\w.]+/, '@something.com') => "bob@something.com"
Let me know I've missed something or if I'm not understanding the question correctly.
marcgg : I totally forgot that you could use regex with gsub... I officially lost my mind. Thanks a lot!jerhinesmith : 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.marcgg : 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 ^^ -
You can use regexps in strings indexes too:
email = "bob@example.com" replace = "foobar.invalid" email[/@.*/] = "@#{replace}"
If you don't want to modify
email
:(new = email.dup)[/@.*/] = "@#{replace}" p [email,new] # => ["bob@example.com", "bob@foobar.invalid"]
-
Another approach, avoiding regular expressions, is to split and join
new = [email.split('@').first, "foobar.invalid"].join('@')
0 comments:
Post a Comment