How to delete specific characters from a string in Ruby?

前端 未结 5 1831
失恋的感觉
失恋的感觉 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:42

    If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:

    s = "((String1))"
    s = s[2...-2]
    p s # => "String1"
    

    If you want to remove all parentheses from the string you can use the delete method on the string class:

    s = "((String1))"
    s.delete! '()'
    p s #  => "String1"
    

提交回复
热议问题