When we check the documentation, below is the syntax for String take method in the Groovy language.
public static CharSequence take(CharSequence self, int num)Since the char sequence is itself, then there is only one parameter which is the number num. And this is the official example from the documentation:
def text = "Groovy" assert text.take( 0 ) == '' assert text.take( 2 ) == 'Gr' assert text.take( 7 ) == 'Groovy'
"Testing".take(n)Is almost equivalent to
What this mean is the Groovy String take method takes the first n characters of the String and return it to the caller. For example:
def myString = "HelloWorld" println myString.take(3) println myString.take(5) println myString.take(7)
The output is below.
Hel Hello HelloWo
The code we show above is equivalent to:
def myString = "HelloWorld" println myString.substring(0,3) println myString.substring(0,5) println myString.substring(0,7)But what if we use a big index greater than the length of the String? This code:
But if we use substring
println "ABC".take.substring(0,5)Will result to an exception.