Ruby multiple string replacement

后端 未结 7 1223
遇见更好的自我
遇见更好的自我 2020-12-02 07:17
str = \"Hello☺ World☹\"

Expected output is:

\"Hello:) World:(\"

I can do this: str.gsub(\"☺\", \":)\").gsu

相关标签:
7条回答
  • 2020-12-02 07:54

    Late to the party but if you wanted to replace certain chars with one, you could use a regex

    string_to_replace.gsub(/_|,| /, '-')
    

    In this example, gsub is replacing underscores(_), commas (,) or ( ) with a dash (-)

    0 讨论(0)
  • 2020-12-02 07:54

    Riffing on naren's answer above, I'd go with

    tr = {'a' => '1', 'b' => '2', 'z' => '26'}
    mystring.gsub(/[#{tr.keys}]/, tr)
    

    So 'zebraazzeebra'.gsub(/[#{tr.keys}]/, tr) returns "26e2r112626ee2r1"

    0 讨论(0)
  • 2020-12-02 08:01

    Another simple way, and yet easy to read is the following:

    str = '12 ene 2013'
    map = {'ene' => 'jan', 'abr'=>'apr', 'dic'=>'dec'}
    map.each {|k,v| str.sub!(k,v)}
    puts str # '12 jan 2013'
    
    0 讨论(0)
  • 2020-12-02 08:05

    You could do something like this:

    replacements = [ ["☺", ":)"], ["☹", ":("] ]
    replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}
    

    There may be a more efficient solution, but this at least makes the code a bit cleaner

    0 讨论(0)
  • 2020-12-02 08:06

    Set up a mapping table:

    map = {'☺' => ':)', '☹' => ':(' }
    

    Then build a regex:

    re = Regexp.new(map.keys.map { |x| Regexp.escape(x) }.join('|'))
    

    And finally, gsub:

    s = str.gsub(re, map)
    

    If you're stuck in 1.8 land, then:

    s = str.gsub(re) { |m| map[m] }
    

    You need the Regexp.escape in there in case anything you want to replace has a special meaning within a regex. Or, thanks to steenslag, you could use:

    re = Regexp.union(map.keys)
    

    and the quoting will be take care of for you.

    0 讨论(0)
  • 2020-12-02 08:11

    You can also use tr to replace multiple characters in a string at once,

    Eg., replace "h" to "m" and "l" to "t"

    "hello".tr("hl", "mt")
     => "metto"
    

    looks simple, neat and faster (not much difference though) than gsub

    puts Benchmark.measure {"hello".tr("hl", "mt") }
      0.000000   0.000000   0.000000 (  0.000007)
    
    puts Benchmark.measure{"hello".gsub(/[hl]/, 'h' => 'm', 'l' => 't') }
      0.000000   0.000000   0.000000 (  0.000021)
    
    0 讨论(0)
提交回复
热议问题