Issue #15899 has been updated by shevegen (Robert A. Heiler).


I can see where it may be useful, since it could shorten code like this:
    
    first_part = "hello world!".split(' ').first

To:

    first_part = "hello world!.before(' ')

It is not a huge improvement in my opinion, though. (My comment here has
not yet addressed the other part about using regexes - see a bit later for
that.)

I am not a big fan of the names, though. I somehow associate #before and #after
more with time-based operations; and rack/sinatra middleware (route) filters.

I do not have a better or alternative suggestion, although since we already have
delete_prefix, perhaps we could have some methods that return the desired prefix
instead (or suffix).

As for lack of regex support, I think sawa already pointed out that it may be
better to reason for changing delete_prefix and delete_suffix instead. That way
your demonstrated use case could be simplified as well.

----------------------------------------
Feature #15899: String#before and String#after
https://bugs.ruby-lang.org/issues/15899#change-78353

* Author: kke (Kimmo Lehto)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
There  seems to be no methods for getting a substring before or after a marker.

Too often I see and have to resort to variations of:

``` ruby
str[/(.+?);/, 1]
str.split(';').first
substr, _ = str.split(';', 2)
str.sub(/.*;/, '')
str[0...str.index(';')]
```

These create intermediate objects or/and are ugly.

The `String#delete_suffix` and `String#delete_prefix` do not accept regexps and thus only can be used if you first figure out the full prefix or suffix.

For this reason, I suggest something like:

``` ruby
> str = 'application/json; charset=utf-8'
> str.before(';')
=> "application/json"
> str.after(';')
=> " charset=utf-8"
```

What should happen if the marker isn't found? In my opinion, `before` should return the full string and `after` an empty string. 





-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>