2009-12-29 66 views
3

我正在经历railstutorial,看到一个班轮以下红宝石oneliner VS常规

('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

回答

3

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

('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"} 
+2

好...略短:。( 'A' .. 'Z')toList(){排序Math.random()} [1..7] .join()+“。heroku.com” – mbrevoort 2009-12-29 07:37:23

+0

请注意,在Java 7中,它们有时会失败,因为它们默认情况下会使用Timsort,并且预计会比较2值保持不变。 – 2013-10-31 10:23:31

2

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

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

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

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

我最喜欢这一款;我认为这是Groovier解决方案= D尽管我认为使用Collections.shuffle来完成扩展方法中的工作会更清楚一些。 – epidemian 2011-11-11 02:09:59

0

这是我的尝试。这是一个单线,但允许重复字符。它不会执行随机播放,尽管它​​会为随机域名生成合适的输出。

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

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

这绝对不是因为红宝石对方漂亮,但正如特德mentioned,这主要是因为这样的事实shuffle方法是Collections中的一种静态方法。

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

我使用的传播运营商招范围转换成一个列表:)