From: kimmo.lehto@... Date: 2019-06-06T07:00:11+00:00 Subject: [ruby-core:92995] [Ruby trunk Feature#15899] String#before and String#after Issue #15899 has been updated by kke (Kimmo Lehto). > Using partition looks reasonable, and it can accept regexes. It also has the problem of creating extra objects that you need to discard with `_` or assign and just leave unused. > 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. How about `str.preceding(';')` and `str.following(';')`? Perhaps `str.prior_to(';')` and `str.behind(';')`? Possibility of opposite reading direction can make these problematic. `str.left_from(';')`, `str.right_from(';')`? Sounds a bit clunky. Head and tail could be the unixy choice and more versatile for other use cases. ```ruby class String def head(count = 10, separator = "\n") ... end def tail(count = 10, separator = "\n") ... end end ``` For my example use case, it would become: ```ruby str = "application/json; charset=utf-8" mime = str.head(1, ';') labels = str.tail(1, ';') ``` And to emulate something like `$ curl xttp://x.example.com | head` you would use `response.body.head` ---------------------------------------- Feature #15899: String#before and String#after https://bugs.ruby-lang.org/issues/15899#change-78373 * 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: