Pradip sakhavala
Pradip sakhavala

Reputation: 119

How to interpolate String in Groovy?

I have multiple variables of list types. I have another list type variable which holds the all variables name as values.

def A = ['abc','def','ghi']
def B = ['123','456','789']
def C = ['ABC','DEF','GHI']

def masterList = ['A','B','C']

masterList.each {

    println "${${it}}"

}

I want output as

'abc','def','ghi'

'123','456','789'

'ABC','DEF','GHI'

Upvotes: 1

Views: 473

Answers (4)

Trebla
Trebla

Reputation: 1172

Though this will depend on your use case, the following works just fine... as long as your variables are class-level variables...

class MyClass {
  def A = ['abc','def','ghi']
  def B = ['123','456','789']
  def C = ['ABC','DEF','GHI']

  def test(String role, String group) {
    def masterList = ['A','B','C']
    masterList.each { it ->
      println(" ${it} = ${this[it]}")
    }
  }
}

Results:

A = [abc, def, ghi]
B = [123, 456, 789]
C = [ABC, DEF, GHI]

Upvotes: 0

daggett
daggett

Reputation: 28564

if it's a script then this will work:

A = ['abc','def','ghi']
B = ['123','456','789']
C = ['ABC','DEF','GHI']

def masterList = ['A','B','C']

masterList.each {
    println this."$it"
}

note that there is no def in front of A,B,C

Upvotes: 2

Ivar
Ivar

Reputation: 4891

If it would be in a class:

class Foo {
    def A = ['abc','def','ghi']
    def B = ['123','456','789']
    def C = ['ABC','DEF','GHI']
}

Foo foo = new Foo()
def masterList = ['A','B','C']
masterList.each {
    println foo[it]
}

Upvotes: 0

ernest_k
ernest_k

Reputation: 45309

You can't reference dynamically those variables, if they're local-scoped.

Solution 1: use a map for your lists:

def map = ['A': ['abc','def','ghi'],
           'B': ['123','456','789']
           'C': ['ABC','DEF','GHI']]

And then

masterList.each {println map[it]}

Solution 2: make A, B, and C instance variables of the current class (if they are not already), after which you can read those properties dynamically using the bracket notation:

masterList.each {println this[it]}

Upvotes: 1

Related Questions