What's the easiest way in Ruby to interchange a part of a string with another value. Let's say that I have an email, and I want to check it on two domains, but I don't know which one I'll get as an input. The app I'm building should work with @gmail.com and @googlemail.com domains.
Example:
swap_string '[email protected]' # >>[email protected]
swap_string '[email protected]' # >>[email protected]
Assuming googlemail.com
and gmail.com
are the only two possibilities, you can use sub
to replace a pattern with given replacement:
def swap_string(str)
if str =~ /gmail.com$/
str.sub("gmail.com","googlemail.com")
else
str.sub("googlemail.com","gmail.com")
end
end
swap_string '[email protected]'
# => "[email protected]"
swap_string '[email protected]'
# => "[email protected]"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments