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

前端 未结 5 1942
温柔的废话
温柔的废话 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:37
    str = "Hello World"
    stopchar = 'W'
    str.sub /#{stopchar}.+/, stopchar
    #=> "Hello W"
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-12-29 02:47

    I'm surprised nobody suggested to use 'gsub'

    irb> "truncate".gsub(/a.*/, 'a')
    => "trunca"
    

    The bang version of gsub can be used to modify the string.

    0 讨论(0)
  • 2020-12-29 02:50

    I find that "Part1?Part2".split('?')[0] is easier to read.

    0 讨论(0)
  • 2020-12-29 02:51
    new_str = str.slice(0..(str.index('blah')))
    

    alt text

    0 讨论(0)
提交回复
热议问题