views:

413

answers:

5

Hey, i try to trim each string item of an list in groovy

list.each() { it = it.trim(); }

But this only works within the closure, in the list the strings are still " foo", "bar " and " groovy ".

How can i achieve that?

+7  A: 
list = list.collect { it.trim() }
sepp2k
list = list.collect { it.trim() }ty
codedevour
Right, can't leave off parens with methods without parameters. Fixed.
sepp2k
+2  A: 

According to the Groovy Quick Start, using collect will collect the values returned from the closure.

Here's a little example using the Groovy Shell:

groovy:000> ["a    ", "  b"].collect { it.trim() }
===> [a, b]
coobird
A: 

@sepp2k i think that works in ruby

and this works in groovy list = list.collect() { it.trim(); }

kiki
+4  A: 

You could also use the spread operator:

def list = [" foo", "bar ", " groovy "]
list = list*.trim()
assert "foo" == list[0]
assert "bar" == list[1]
assert "groovy" == list[2]
John Wagenleitner
A: 

If you really had to modify the list in place, you could use list.eachWithIndex { item, idx -> list[idx] = item.trim() }.

collect() is way better.

John Stoneham