Issue #15899 has been updated by kke (Kimmo Lehto).


How about `first` and `last`?

```ruby
'hello world'.first(2)
 => 'he'
'hello world'.last(2)
 => 'ld'
'hello world'.first
 => 'h'
'hello world'.last
 => 'd'
'hello world'.first(1, ' ')
 => 'hello'
'hello world'.last(1, ' ')
 => 'world'
'application/json; charset=utf-8'.first(1, ';')
 => 'application/json'
```


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

* 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>