assign “it” in each iteration (groovy)

2019-04-04 23:37发布

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?

5条回答
Juvenile、少年°
2楼-- · 2019-04-05 00:01

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]
查看更多
疯言疯语
3楼-- · 2019-04-05 00:02

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-04-05 00:04
list = list.collect { it.trim() }
查看更多
Evening l夕情丶
5楼-- · 2019-04-05 00:12

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]
查看更多
啃猪蹄的小仙女
6楼-- · 2019-04-05 00:22

@sepp2k i think that works in ruby

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

查看更多
登录 后发表回答