How do I remove a substring after a certain character in a string using Ruby?

前端 未结 5 1944
温柔的废话
温柔的废话 2020-12-29 02:05

How do I remove a substring after a certain character in a string using Ruby?

5条回答
  •  时光取名叫无心
    2020-12-29 02:41

    A special case is if you have multiple occurrences of the same character and you want to delete from the last occurrence to the end (not the first one). Following what Jacob suggested, you just have to use rindex instead of index as rindex gets the index of the character in the string but starting from the end. Something like this:

    str = '/path/to/some_file'
    puts str.slice(0, str.index('/')) # => ""
    puts str.slice(0, str.rindex('/')) # => "/path/to"
    

提交回复
热议问题