简体   繁体   中英

Replace 2 strings at the same time?

how can I replace 2 strings in the same time? for example let's say I have string like this:

str1 = "AAAA BBBB CCCC DDDD"

i want to replace every "AAAA" with "CCCC" and every "CCCC" with "AAAA" but if i did:

str1.gsub("AAAA","CCCC") # CCCC BBBB CCCC DDDD

str1.gsub("CCCC","AAAA") # AAAA BBBB AAAA DDDD

what I want str1 to be " CCCC BBBB AAAA DDDD"

General answer:
Use a regex to match both AAAA and CCCC, then substitute each match with CCCC and AAAA respectively.

edit to clear up the confusion

str1.gsub(/(AAAA|CCCC)/) { $1 == 'AAAA' ? 'CCCC' : 'AAAA' }

edit i thought of a more elegant way too :)

str1.gsub(/((AAAA)|(CCCC))/) { $2 ? 'CCCC' : 'AAAA' }

Is it an option for you to replace AAAA with something else first and then proceed?

str1.gsub("AAAA","WXYZ") # WXYZ BBBB CCCC DDDD
str1.gsub("CCCC","AAAA") # WXYZ BBBB AAAA DDDD
str1.gsub("WXYZ","CCCC") # CCCC BBBB AAAA DDDD

A solution (although something based around regex would be best) would be something along the lines of creating a replacement hash as such, which can be extended as needed. I just quickly put this together to demonstrate. I'm sure with a bit more love and care you can come up with something more elegant that works along the same lines as this implementation only works for strings with spaces.

str1 = "AAAA BBBB CCCC DDDD"    
replacements = { "AAAA" => "CCCC", "CCCC" => "AAAA", "XXXX" => "ZZZZ" } # etc...

new_string = ""
str1.split(" ").each do |s| 
    new_string += replacements[s] || s
    new_string += " "
end

puts new_string # CCCC BBBB AAAA DDDD 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM