Take the 2-minute tour ×

I am new to groovy and thats why I can't figure one thing out. I have ant task with groovy class that is supposed to read lines from property file and switch some of the property.values, for example 1 with "One", 2 with "Two" etc. I have extracted the values so I've got 1,2,3 etc or 5,7,1 and now the problem starts I know about the replaceAll method, but is it possible to somehow make it more flexible? Or if I want to change 1 2 3 I have to define 3 replaceAll methods ("1", "One") ("2","Two") ("3", "Three") ? Oh and yes, switch the values only on output.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

You could use a collect and a switch (assuming I understand the question:

def a = [ 1, 4, 2 ]

def b = a.collect {
  switch( it ) {
    case 1  : 'One' ; break
    case 2  : 'Two' ; break
    case 3  : 'Three' ; break
    default : it

assert b = [ 'One', 4, 'Two' ]

// And the other way

def c = b.collect {
  switch( it ) {
    case 'One'   : 1 ; break
    case 'Two'   : 2 ; break
    case 'Three' : 3 ; break
    default      : it

assert c == a 
share|improve this answer
Thanks for this idea, got one more question, this works perfect, but when I'm trying to do it the other way ( from string to 'int' ) it does not find any case, doing it like case 'ONE' : print '1' and collecting it property.value.collect what is wrong with my idea? –  user2141889 May 20 '13 at 10:21
@user2141889 not sure I understand, but I've updated my answer to change b back the other way into a again... Does that help? –  tim_yates May 20 '13 at 10:25
Yes thats exactly what I was looking for, thanks. –  user2141889 May 20 '13 at 10:44
add comment

Your Answer


