Skip to content

Commit

Permalink
Give .chomp the possibility to specify a needle (#4739)
Browse files Browse the repository at this point in the history
Basically:

    say "foobar".chomp("bar");  # foo
    say "foobar".chomp("baz");  # foobar
  • Loading branch information
lizmat committed Feb 12, 2022
1 parent 83b2417 commit cccc3e8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/core.c/Cool.pm6
Expand Up @@ -109,8 +109,9 @@ my class Cool { # declared in BOOTSTRAP
proto method flip(*%) {*}
multi method flip(Cool:D:) { self.Str.flip }

proto method chomp(*%) {*}
proto method chomp($?, *%) {*}
multi method chomp(Cool:D:) { self.Str.chomp }
multi method chomp(Cool:D: Cool:D $needle) { self.Str.chomp($needle.Str) }

proto method chop(|) {*}
multi method chop(Cool:D:) { self.Str.chop }
Expand Down
6 changes: 6 additions & 0 deletions src/core.c/Str.pm6
Expand Up @@ -124,6 +124,12 @@ my class Str does Stringy { # declared in BOOTSTRAP
self
)
}
multi method chomp(Str:D: Str:D $needle--> Str:D) {
my int $offset = nqp::sub_i(nqp::chars(self),nqp::chars($needle));
nqp::eqat(self,$needle,$offset)
?? nqp::substr(self,0,$offset)
!! self
}

multi method chop(Str:D: --> Str:D) {
nqp::box_s(
Expand Down

1 comment on commit cccc3e8

@0racle
Copy link
Contributor

@0racle 0racle commented on cccc3e8 Feb 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have previously thought about this feature, but thought it might be a better fit for trim and friends (trim-leading , trim-trailing).

Indeed, Python's trim-family equivalents (strip, lstrip, and rstrip) kind of do this, but tread the argument as a list of possible removals

>>> 'foobar'.rstrip('abr')
'foo'

Which Raku can replicate with subst, a Regex character class, and an anchor... but perhaps a future feature for Raku trim might be - yes, add this needle functionality from chomp - but also add the ability to supply a Regex, eg. "barxbar".trim-trailing(/<[arb]>/). Is that too much TIMTOWTDI?

Please sign in to comment.