Ruby multiple string replacement

后端 未结 7 1224
遇见更好的自我
遇见更好的自我 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:17

    Since Ruby 1.9.2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.

    Like this:

    'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"
    '(0) 123-123.123'.gsub(/[()-,. ]/, '')    #=> "0123123123"
    

    In Ruby 1.8.7, you would achieve the same with a block:

    dict = { 'e' => 3, 'o' => '*' }
    'hello'.gsub /[eo]/ do |match|
       dict[match.to_s]
     end #=> "h3ll*"
    
    0 讨论(0)
提交回复
热议问题