How to delete specific characters from a string in Ruby?

前端 未结 5 1820
失恋的感觉
失恋的感觉 2021-02-01 00:04

I have several strings that look like this:

\"((String1))\"

They are all different lengths. How could I remove the parentheses from all these s

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 00:58

    For those coming across this and looking for performance, it looks like #delete and #tr are about the same in speed and 2-4x faster than gsub.

    text = "Here is a string with / some forwa/rd slashes"
    tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
    # tr.total => 0.01
    delete = Benchmark.measure { 10000.times { text.delete('/') } }
    # delete.total => 0.01
    gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
    # gsub.total => 0.02 - 0.04
    

提交回复
热议问题