Ruby multiple string replacement

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

Expected output is:

\"Hello:) World:(\"

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

7条回答
  •  北荒
    北荒 (楼主)
    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)
    

提交回复
热议问题