calling .each{} on IntRange returns the range not each integer

GroovyIntRangeEach

Groovy Problem Overview


I think I've got some funny expectations... I want to iterate the numbers from 1 to 10. As a while loop it goes like this:

def countMe = 1
while (countMe<11) {
  println countMe
  countMe++
}

I was expecting that the following would do this also:

[1..10].each { println it }

But it actually prints the IntRange, not each Integer in the range. What is the (syntactically) closest way to my [x..y].each{} fantasy to get each of a list of numbers?

Groovy Solutions


Solution 1 - Groovy

Use parentheses not brackets:

(1..10).each{println it}

[1..10] is a list of length 1 containing a single range.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeyView Question on Stackoverflow
Solution 1 - GroovyEricView Answer on Stackoverflow