Project

General

Profile

Actions

Feature #15899

open

String#before and String#after

Added by kke (Kimmo Lehto) over 5 years ago. Updated about 5 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:92972]

Description

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:

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:

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


Files

test.rb (712 Bytes) test.rb edd314159 (Edd Morgan), 07/09/2019 06:33 PM
test_mem.rb (326 Bytes) test_mem.rb edd314159 (Edd Morgan), 07/09/2019 06:33 PM
2269.diff (3.77 KB) 2269.diff edd314159 (Edd Morgan), 07/09/2019 06:33 PM
Actions

Also available in: Atom PDF

Like0
Like0Like1Like0Like0Like1Like0Like0Like0