Posted By

hansamann on 02/22/07


Tagged

lists groovyseries ranges


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

jsbournival
bootz15
hendersk
mbanfi
adaptives


Groovy Series: Ranges


 / Published in: Groovy
 

URL: http://hansamann.podspot.de/files/grails_podcast_episode_35.mp3

This snippet gives you some interesting examples what you can do with Groovy Ranges. Listen to the audio to get the best learning experience. Simply right-click on the title above to download the mp3 file of this part of the series.

The Groovy Series is part of the Grails Podcast and can be subscribed to via: http://hansamann.podspot.de/rss. The series is produced by Dierk K├Ânig and Sven Haiges, further information about the topic of this episode can be found in the book

Groovy in Action - http://groovy.canoo.com/gina

  1. //Ranges
  2.  
  3. //inclusive range
  4. def inclusiveRange = 1..10
  5. assert inclusiveRange instanceof List
  6. assert inclusiveRange.size() == 10
  7. assert inclusiveRange.contains(10)
  8.  
  9. //exclusive range
  10. def exclusiveRange = 1..<10
  11. assert exclusiveRange.size() == 9
  12. assert !exclusiveRange.contains(10)
  13.  
  14. //sequence from negative to positive values
  15. def negativeToPositive = -5..5
  16. assert negativeToPositive.join(',') == '-5,-4,-3,-2,-1,0,1,2,3,4,5'
  17.  
  18. //negative sequence
  19. def negativeRange = -5..<-10
  20. assert negativeRange.join(',') == '-5,-6,-7,-8,-9'
  21.  
  22. //we need no for loop :-)
  23. //but don't forget the braces around the range...
  24. (1..10).each {
  25. out << it
  26. }
  27. assert out.toString() == '12345678910'
  28.  
  29. //but we can use a for loop if we want
  30. def range = 1..10
  31. for (i in range) {
  32. out << i
  33. }
  34. assert out.toString() == '12345678910'
  35.  
  36. //we can also step through a range
  37. assert (1..10).step(2).join(',') == '1,3,5,7,9'
  38.  
  39. //some more fun with groovy
  40. assert (1..10).reverse().join(',') == '10,9,8,7,6,5,4,3,2,1'
  41. assert (1..10).grep{ it > 5}.size() == 5
  42.  
  43. //using ranges to create a sublist
  44. def largeList = [1,2,3,4,5,6,7,8,9,10]
  45. assert largeList[0..4] == [1,2,3,4,5]
  46. assert largeList[0..<4] == [1,2,3,4]
  47. assert largeList[-1..-3] == [10,9,8]
  48.  
  49. //ranges can be used with grep... here using grep with a list
  50. assert [1,2,3,4,5,6,7,8,9,10,11,12].grep(5..10) == [5,6,7,8,9,10]

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: adaptives on February 7, 2009

Nice example and accompanying podcast. I started out thinking 'Ranges' are simple, but now they seem a bit confusing. I think I will have to revisit this topic in some time again.

You need to login to post a comment.