Created
October 11, 2010 05:44
-
-
Save touchez-du-bois/620045 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g100pon #64 クロージャとdelegate | |
// 要素を表示するクロージャ | |
def printElements = { | |
delegate.each { | |
println it | |
} | |
} | |
// クラスにクロージャを追加 | |
ArrayList.metaClass.printElements = printElements | |
LinkedHashMap.metaClass.printElements = printElements | |
String.metaClass.printElements = printElements | |
// 出力結果を取得できるように標準出力を切り替え | |
def prevOut = System.out | |
def byteArray = new ByteArrayOutputStream() | |
System.out = new PrintStream(byteArray, true, 'UTF-8') | |
[1,2,3,4,5].printElements() | |
assert ['1','2','3','4','5'] == byteArray.toString().split("\n") | |
byteArray.reset() | |
[a:1, b:2, c:3, d:4, e:5].printElements() | |
assert ['a=1','b=2','c=3','d=4','e=5'] == byteArray.toString().split("\n") | |
byteArray.reset() | |
"Groovy".printElements() | |
assert ['G','r','o','o','v','y'] == byteArray.toString().split("\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment