10raw
10raw

Reputation: 574

How to create a new variable using old variable and assiging it some value in groovy

I am trying to create a new variable using the name of old variable (appending old variable with some string) and assign that new variable with some value as in example below in jenkinsfile using groovy:

def var1= "value1"
def var1 + "_someval"= 50  // creating a new variable which will have name value1_someval and it will have value 50
print( "value for value1_someval  is" + value1_someval) 
// expected output is that new  variable value1_someval is created with value 50 assigned to it. 

Upvotes: 0

Views: 606

Answers (2)

10raw
10raw

Reputation: 574

I got this working by using quoted identifies in following way:

def map = [:]
def lastchar = "_someval"

map."val1${lastchar}" = 50

//assert map.'val1_someval' == 50

print map.VA_REPOSITORY_VERSION

prints out 50 as output

Upvotes: 0

ou_ryperd
ou_ryperd

Reputation: 2133

Whatyou want to do is possible, but it's messy and can cause problems. I strongly suggest that you use a list instead:

List li = []
li[0] = "value1"
li[1] = 50

Upvotes: 1

Related Questions