assign “it” in each iteration (groovy)

可紊 提交于 2019-12-04 01:33:13
list = list.collect { it.trim() }

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]

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]

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.

@sepp2k i think that works in ruby

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!