Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby oneliner vs groovy

i was going through railstutorial and saw the following one liner

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

it creates random 7 character domain name like following:

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

I tried converting the 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 the above be improved and made to a one liner? I tried to make the above code shorter by

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

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

like image 734
Omnipresent Avatar asked Jul 24 '26 06:07

Omnipresent


2 Answers

Not having shuffle built-in adds the most to the length, but here's a one liner that'll do it:

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

Yours doesn't work because Collections.shuffle does an inplace shuffle but doesn't return anything. To use that as a one liner, you'd need to do this:

('a'..'z').toList().with{Collections.shuffle(it); it[1..7].join()+".heroku.com"}
like image 70
Ted Naleid Avatar answered Jul 26 '26 02:07

Ted Naleid


It isn't a one-liner, but another Groovy way to do this is to add a shuffle method to String...

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

And then you have something very Ruby-like...

('a'..'z').join().shuffle(0..7)+'.heroku.com'
like image 25
yawmark Avatar answered Jul 26 '26 02:07

yawmark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!