Swap part of a string in Ruby

Sebastian

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]
shivam

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Swap characters in string

From Dev

How to swap two characters in a string?

From Dev

How to swap columns and rows in a matrix with Ruby

From Dev

Swap keys in ruby hash

From Dev

Swap two letters in a string

From Dev

Swap two sides of an = in a string

From Dev

How to use regex to swap number position in a string in ruby?

From Dev

How to swap characters in a string

From Dev

Sorting part of an array in Ruby

From Dev

How to check if string contains a part of an array in Ruby?

From Dev

Error in sample ruby program to swap element in an array

From Dev

How can I get a part of a string from a starting point to the end of the string using Ruby

From Dev

Swap 2 letter part of a url in htaccess file

From Dev

Kotlin: how to swap character in String

From Dev

Parse string and swap all occurrences

From Dev

Javascript replace part with part of part in string?

From Dev

how to remove part of a string (not just replace it) via regex ruby

From Dev

Swap keys in ruby hash

From Dev

Swap two sides of an = in a string

From Dev

Swap string case - swift

From Dev

How to check if string contains a part of an array in Ruby?

From Dev

javascript swap and replace string

From Dev

How can I get a part of a string from a starting point to the end of the string using Ruby

From Dev

Meaning of the swap part in the top command

From Dev

Swap numerals in a String by byte operation

From Dev

How can I output the AM/PM part of a string received in military time using Ruby?

From Dev

Colorise part of string in Ruby

From Dev

String Swap Before and After Comma

From Dev

Compare two different string with the same part in Ruby on Rails

Related Related

HotTag

Archive