nemo_kazのメモ [Groovyライフ]

2012-03-20 [Groovy] マイ・コーディング・チートシート

[Groovy] マイ・コーディングチートシート

Groovy Codingする時に、ちょっと書き方を思い出せない時にちら見するためのカンニングペーパーです。

色々なところから集めてきています。


/** Cheat sheet */

/** List */
ll = [11, 12, 13, 14]
[11, 12, 13, 14].add(2, 15)     // [11, 12, 15, 13, 14]
[11, 12, 13, 14].add([15, 16])  // [11, 12, 13, 14, 15, 16]
[11, 12, 13, 14].get(1)         // 12
[11, 12, 13, 14].isEmpty()      // false
assert ll.size()                ==4
[11, 12, [13, 14]].flatten()    // [11, 12, 13, 14]
assert ll.getAt(1)              == 12
assert ll.getAt(1..2)           == [12, 13]
[11, 12, 13, 14].getAt([2, 3])  // [13, 14]
[11, 12, 13, 14].intersect([13, 14, 15]) // [13, 14]
assert ll.pop()                 ==14
[11, 12, 13].add(14)            // [11, 12, 13, 14]
assert ll.reverse()             == [13, 12, 11]
assert ll.sort()                == [11, 12, 13]
assert ll.max()                 == 13

List lst = [1,2,3,4,5,6,7]
assert lst.count {it % 2 == 0 } == 3
assert lst.grep {it % 2 == 0 } == [2,4,6]
assert lst[0] == 1
assert lst[-1] == 7 // 最後の要素
assert lst << [8,9,10] == [1,2,3,4,5,6,7,[8,9,10]]


/** Map */
def mp = ['Ami':111, 'Bob':222 ]
mp.put('Carl',333) 
assert mp.containsKey('Bob') == true
assert mp.get('Ami', 111)    == 111
assert mp.get('Bob')         == 222
assert mp.get('Billy')       == null
println mp.keySet()          // [Ami, Bob, Carl]
assert mp.size()             == 3
assert mp['Bob']             == 222
assert mp.count {k,v -> k == 'Bob' || v==111 } == 2
assert mp.containsKey('Ami')


/** range */
def twentiethCentury = 1900..1999 // Range literal
def reversedTen = 10..1     // Reversed Range
assert twentiethCentury.size()    == 100
assert twentiethCentury.get(0)    == 1900
assert twentiethCentury.getFrom() == 1900
assert twentiethCentury.getTo()   == 1999
assert twentiethCentury.contains(2000) == false
assert twentiethCentury.subList(0, 5) == 1900..1904
assert reversedTen[2] == 8
assert reversedTen.isReverse() == true


/** String */
def hello='Hello'
assert hello.compareToIgnoreCase('hello')  == 0
assert hello.concat('world')           == 'Helloworld'
assert hello.endsWith('lo')            == true
assert hello.equalsIgnoreCase('hello') == true
assert hello.indexOf('lo')             == 3
assert 'Hello world'.indexOf('o', 6)   == 7
assert hello.matches('Hello')          == true
assert hello.matches('He')             == false
assert hello.replaceAll('l', 'L')      == 'HeLLo'
assert 'Hello world'.split('l')        == ['He', '', 'o wor', 'd']
assert hello.substring(1)              == 'ello'
assert hello.substring(1, 4)           == 'ell'
assert hello.toUpperCase()             == 'HELLO'
assert hello.center(11)                == '   Hello   '
assert hello.center(3)                 == 'Hello'
assert hello.center(11, '#')           == '###Hello###'
hello.eachMatch('.') { ch -> print ch }  // print H e l l o 
assert hello.getAt(0)                  == 'H'
assert hello.getAt(0..<3)              == 'Hel'
assert hello.getAt([0, 2, 4])          == 'Hlo'
assert "ABCDEFG".getAt( [0, 2, 4] )    == "ACE"
hello.leftShift('world')              // 'Helloworld'
hello << 'world'                      // Hello world  
assert hello.minus('ell')              == 'Ho'
assert hello - 'ell'                   == 'Ho'
assert hello.padLeft(4)                == 'Hello'
assert hello.padLeft(11)               == '      Hello'
assert hello.padLeft(11, '#')          == '######Hello'
assert hello.padRight(4)               == 'Hello'
assert hello.padRight(11)              == 'Hello      '
assert hello.padRight(11, '#')         == 'Hello######'
hello.plus('world')                // Hello world
hello + 'world'                    // Hello world
hello.replaceAll('[a-z]') { ch -> ch.toUpperCase() } // HELLO
assert hello.reverse()                 == 'olleH'
assert hello.toList()                  == ['H', 'e', 'l', 'l', 'o']
hello = 'Hello world'
hello.tokenize()                   // ['Hello', 'world']
hello.tokenize('l')                // ['He', 'o wor', 'd']

assert 'hello my friend.'.tokenize(/ +/)*.capitalize().join(' ') == 'Hello My Friend.'

// 部分除去
str = "goooooooooooooogle"
str = str.toList()
str[1..14] = ''
str = str.join()
assert str == "ggle"

/** Metaclass操作*/
Object.metaClass.divIt = { ->
	if (delegate != 0 ) {
		return Math.round(Math.floor(delegate.toInteger()/2.toDouble()))
	} else {
		return delegate
	}
}
assert 101.divIt()==50
assert 0.divIt()==0

/** Regular expression */
assert "aaa" =~ /a/         // 内包一致
assert "a"   ==~/a/         // 完全一致
assert "AAABBBCCC".replaceAll(/(.*)BBB(.*)/) {m0, m1, m2 -> "${m1}${m2}" } == "AAACCC" // 中間部分削除

/** for */
for (int i: 1 .. 3) { print i+ " " }         // 1 2 3
for (String s: "a" .. "c") { print s + " " } // a b c
String input = "ABC"
for (int i: 0 .. input.size()-1) {print input.getAt(i) + " "}  // Java形式は型宣言必要
for (  i in 0 .. input.size()-1) {print input.getAt(i) + " "}  // Groovy独自形式

/** Math  */
assert Math.round(876.543) == 877 // 四捨五入
assert Math.ceil(876.543)  == 877 // 切り上げ
assert Math.floor(876.543) == 876 // 切り捨て
assert Math.abs(-1)        == 1
assert Math.max(10,20)     == 20
assert Math.sqrt(9)        == 3.0

/** swap */
def list = [1, 2]
Collections.swap(list, 0, 1)
assert [2, 1] == list

def a = 1, b = 2
(a, b) = [b, a]
assert a == 2
assert b == 1

def map = [x:1, y:2]
map.with {
  (x, y) = [y, x]
}
assert [x:2, y:1] == map

class Person {
	def firstname
	def lastname
	Person(f,l) {
		firstname=f
		lastname =l
	}
}
Person p = new Person('First','Last')
println "\nBefore : "+ p.firstname +" "+ p.lastname 
p.with { (firstname, lastname) = "First2 Last2".split() } // ok
println "After  : "+ p.firstname +" "+ p.lastname 

/** Random */

IntRange.metaClass.define {
    random {
        int from = delegate.isReverse() ? to : from
        int to   = delegate.isReverse() ? from : to
        int size = to - from + 1
        (Math.floor(Math.random() * size) + from) as int
    }
}    // 範囲内でランダム

// パーセント計算
Number.metaClass.getProperty = { propertyName ->
    if (propertyName == 'percent') { delegate / 100 }
    else { delegate }
}
assert 20.5.percent== 0.205
assert 20.percent == 0.2


1000.times{
    assert (0..4).random() in (0..4), '0〜4の値がランダムに返ってくるはず'
}
//println (0..4).random() in (0..4)

/** char number  conversion*/
def charset = 'us-ascii'
assert  'groovy'.getBytes(charset) == [103, 114, 111, 111, 118, 121]
assert 'groovy' == new String([103, 114, 111, 111, 118, 121] as byte[], charset) // character codes to string
String.metaClass.static.fromBytes << { charsetName, List bytes -> new String(bytes.toArray() as byte[], charsetName) }
String.metaClass.static.fromBytes << { charsetName, Object... bytes -> new String(bytes as byte[], charsetName) }
assert 'groovy' == String.fromBytes(charset, [103, 114, 111, 111, 118, 121])
assert 'groovy' == String.fromBytes(charset, 103, 114, 111, 111, 118, 121)


/** コレクション操作 */
list = ['a','b','c','d'] 
newList = [] 
list.collect( newList ) { 
  it.toUpperCase() 
} 
assert newList == ["A", "B", "C", "D"]


/** クロージャー */
def clos = { aa, bb ->  aa+bb } 
assert clos( 5, 7 ) == 12


//エルビス演算子 nullなら初期値を代入
def name 
displayName = name ?: 'Anonymous'

Connection: close