I want to assign the array item into variable directly using groovy like this:
def str = "xyz=abc"
def [name, value] = str.split("=")
but groovy doesn't like it. Is there a way to do that (not storing the array result and get the index[0], index[1] from it?).
Thanks,
Splitting a String by comma (,) Here, the variable str is declared with a string with commas (“,”) in between them. The Split function is implemented with “,” as the separator. Whenever the function sees a comma character, it separates the string and the output is a list of substrings between the commas in str.
Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.
You just need parenthesis instead of brackets:
def str = "xyz=abc"
def (name, value) = str.split("=")
Note that you'll need to know how many elements you're expecting or you'll have unexpected results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With