Return string until matched string in Ruby

I'd write a method to make it clear. Something like this, for example:

class String
    def substring_until(substring)
        i = index(substring)
        return self if i.nil?
        i == 0 ? "" : self[0..(i - 1)]
    end
end

Use String#[] method. Like this:

[
  '#foo',
  'foo#bar',
  'fooAptbar',
  'asdfApt'
].map { |str| str[/^(.*)(#|Apt)/, 1] } #=> ["", "foo", "foo", "asdf"]

String splitting is definitely easier and more readable that a regex. For regex, you would need a capture group to get the first match. It will be the same as string splitting

string.split(/#|Apt/, 2).first

Tags:

String

Ruby