最初の の場合assert
、エラー メッセージは問題がどこにあるかを示唆している可能性があります。
Assertion failed:
assert words.size() == 16
| | |
| 14 false
[
line1:, 50, 65, 42
line2:, 123, 456, 352, 753, 1825
line3:, 10, 25, 20, 48, 107
]
いくつかのコンマが欠落しており、words
値が出力される方法が間違っているようです。何が起こっているかというinput.split(/ /)
と、入力文字列をスペースで分割していますが、改行も含まれているため、一部の単語は分割されません'42\nline2:'
。
これをより明確に見るために、inspect
メソッドを使用して、オブジェクトのリテラル形式の文字列を取得できます。
println input.inspect()
// --> '\nline1: 50 65 42\nline2: 123 456 352 753 1825\nline3: 10 25 20 48 107\n'
println input.split(/ /).inspect()
// --> ['\nline1:', '50', '65', '42\nline2:', '123', '456', '352', '753', '1825\nline3:', '10', '25', '20', '48', '107\n']
単語を空白で分割するために、Groovy は便利なパラメーター化されていないsplit
メソッドを追加します。
def words = input.split()
assert words.size() == 16
println words.inspect()
// --> ['line1:', '50', '65', '42', 'line2:', '123', '456', '352', '753', '1825', 'line3:', '10', '25', '20', '48', '107']
また、文字列の行を取得するには、 を使用できますreadLines
。
def lines = input.readLines()
println lines.inspect()
// --> ['', 'line1: 50 65 42', 'line2: 123 456 352 753 1825', 'line3: 10 25 20 48 107']
readLines
ただし、最初の空行があるため (ただし、最後の空行を無視する理由がわかりません)、4 つの要素が返されることに注意してくださいassert lines.size() == 3
。それでも失敗します。
Collection#findAll()
結果のリストを使用するかString#findAll(Pattern)
、入力文字列を直接呼び出して、これらの空の行を除外できます。
def lines = input.readLines().findAll()
assert lines.size() == 3
def lines2 = input.findAll(/\S+/)
assert lines2.size() == 3
assert lines == lines2