Ruby oneliner vs groovy

i went through the railstutorial and saw the next one liner

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

it creates a random 7-character domain name, for example the following:

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

I tried converting one liner to groovy, but I could only come up with:

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

Can this be improved and done on one liner? I tried to make the code above shorter

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

However, apparently, Collections.shuffle(new ArrayList ( ('a'..'z') ))isnull

+3
source share
4 answers

Without a built-in shuffle, it adds most of the length, but here is one liner that will do this:

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

, Groovy - Shuffle String...

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

- Ruby...

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

. , . , .

:

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

, Ruby, , , - , shuffle Collections.

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

:)

0

Source: https://habr.com/ru/post/1726767/


All Articles