Skip to content

Instantly share code, notes, and snippets.

@aesteve
Created January 8, 2016 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aesteve/95a3cc56e061b50357c7 to your computer and use it in GitHub Desktop.
Save aesteve/95a3cc56e061b50357c7 to your computer and use it in GitHub Desktop.
"Write a method which will remove any given character from a String"
// "Write a method which will remove any given character from a String"
// The method will be the 'minus' method 'some string ' - 's' == 'ome tring'
def check() {
assert 'some string' - 's' == 'ome tring'
assert '' - 'a' == ''
assert 'something else' - 'z' == 'something else'
}
// Easy one
String.metaClass.minus { String c -> // careful, String already has a 'minus' method, if we override the one in CharSequence, it won't work
delegate.replaceAll(c, '')
}
check()
// Non-cheating one
String.metaClass.minus { String toRemove ->
StringBuffer buff = ''<<''
delegate.each { c ->
if (c != toRemove) buff << c
}
buff as String
}
check()​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment