Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could you print the variable name in a Groovy list and not the value

If I got a list in Groovy containing 2 or more variables with some value, and I want to see if it contains a given text string I'm doing the following:

def msg = '''
 Hello Mars!
'''

def msg1 = '''
 Hello world!
'''


def list = [msg, msg1]

list.findAll { w -> 
    if(w.contains("Hello"))
    {
        println w
    }
    else
    {
        println "Not there"
    }
}

But instead of printing the value I would like to print the variable name that contains the text. Is that possible with a list or do I need to make a map?

like image 893
Nyegaard Avatar asked Mar 01 '12 07:03

Nyegaard


2 Answers

You need to use a Map, because mapping from keys to values.

def msg = '''
 Hello Mars!
'''

def msg1 = '''
 Hello world!
'''

def map = [msg: msg, msg1: msg1]

map.findAll { key, value -> 
    if (value.contains("Hello")) {
        println key
    }
    else {
        println "Not there"
    }
}
like image 197
Arturo Herrero Avatar answered Oct 13 '22 20:10

Arturo Herrero


If you are running this as a Groovy script, you may use the binding archive instead of a list of variables, but you need to assign the variables without the def (so they become part of the binding). Something like:

aaa = 'Hello World!'
bbb = 'Goodbye all!'
ccc = 'Hello Mars!'

this.binding.variables.each { var ->
    if (var.value ==~ /Hello.*/)
        println "$var.key contains 'Hello'"
}

Output:

aaa contains 'Hello'
ccc contains 'Hello'
like image 4
epidemian Avatar answered Oct 13 '22 21:10

epidemian