我正在经历 railstutorial 并看到下面的一个衬里

('a'..'z').to_a.shuffle[0..7].join

它创建随机7字符域名像下面这样:

 hwpcbmze.heroku.com
 seyjhflo.heroku.com
 jhyicevg.heroku.com

我试图将所述一个衬垫的Groovy但我只想出:

def range = ('a'..'z')
def tempList = new ArrayList (range)
Collections.shuffle(tempList)
println tempList[0..7].join()+".heroku.com"

可以在上述改进和到一个衬片制成?我试图通过

,使上述代码短
println Collections.shuffle(new ArrayList ( ('a'..'z') ))[0..7].join()+".heroku.com"

然而,显然Collections.shuffle(new ArrayList ( ('a'..'z') ))null

有帮助吗?

解决方案

由于没有洗牌内置增添最给长,但这里有一个内衬会做到这一点:

('a'..'z').toList().sort{new Random().nextInt()}[1..7].join()+".heroku.com"

你的没有工作,因为Collections.shuffle确实就地洗牌,但不返回任何东西。要使用它作为一个衬垫,你需要做到这一点:

('a'..'z').toList().with{Collections.shuffle(it); it[1..7].join()+".heroku.com"}

其他提示

这是不是一个衬垫,但另一个Groovy的方式做,这是一个洗牌方法添加到字符串...

String.metaClass.shuffle = { range ->
def r = new Random()
delegate.toList().sort { r.nextInt() }.join()[range]}

然后你有一些非常红宝石般的...

('a'..'z').join().shuffle(0..7)+'.heroku.com'

这是我的尝试。这是一个班轮,但允许字符重复。它不执行混洗,尽管它产生合适的输出用于随机域名。

我张贴它作为一个递归的匿名闭合的示例:

{ i -> i > 0 ? "${(97 + new Random().nextInt(26) as char)}" + call(i-1) : "" }.call(7) + ".heroku.com"
scroll top