0

What I want to do:
I have a variable that needs to be assigned a value that changes every time the method is called. Every time the code runs the it cycles between two values, either string1 or string2.
This would be a function that is part of a Groovy script for a Jenkins pipeline: first time around the variable will be assigned to string1, second time string2, third time string1 again and so on and so forth. I have tried this snippet but using Random it repeats the string, I just want it to cycle between the two values.
Python has a choice property for random to restrict the choices, cannot find one in groovy. How to choose randomly between two values?

def test = ""
def string1or2(test) {
    test = ["string", "string2"]
    assert test instanceof List
    def rand = test.sort {Math.random()}
    println(rand[0])
    return(rand[0])
}
string1or2(test)
Kev
  • 13
  • 3

1 Answers1

0

Try this:

import groovy.transform.Field

@Field
def index = 0
@Field
def options = ['string1', 'string2']

def string1or2() {
    return options[(index++) % options.size()]
}

// print 10 values
10.times { println string1or2() }
Renato
  • 12,940
  • 3
  • 54
  • 85