ruby oneliner 与 groovy
我正在浏览 railstutorial 并看到以下一行,
('a'..'z').to_a.shuffle[0..7].join
它创建随机 7 个字符域名如下:
hwpcbmze.heroku.com
seyjhflo.heroku.com
jhyicevg.heroku.com
我尝试将 one liner 转换为 groovy,但我只能想出:
def range = ('a'..'z')
def tempList = new ArrayList (range)
Collections.shuffle(tempList)
println tempList[0..7].join()+".heroku.com"
可以改进上述内容并将其制作为 one liner 吗?我试图使上面的代码更短
println Collections.shuffle(new ArrayList ( ('a'..'z') ))[0..7].join()+".heroku.com"
但是,显然 Collections.shuffle(new ArrayList ( ('a'..'z') ))
是 null
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有内置的 shuffle 会增加最多的长度,但这里有一个衬垫可以做到这一点:
你的衬垫不起作用,因为 Collections.shuffle 会进行就地洗牌,但不会返回任何内容。要将其用作单行,您需要执行以下操作:
Not having shuffle built-in adds the most to the length, but here's a one liner that'll do it:
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:
这不是一句简单的话,但另一种 Groovy 方法是向 String 添加 shuffle 方法...
然后你就得到了一些非常类似于 Ruby 的东西...
It isn't a one-liner, but another Groovy way to do this is to add a shuffle method to String...
And then you have something very Ruby-like...
这是我的尝试。它是一句单行语句,但允许重复字符。它不执行随机播放,但它会为随机域名生成合适的输出。
我将其作为递归匿名闭包的示例发布:
This is my attempt. It is a one-liner but allows repetition of characters. It does not perform a shuffle, though it generates suitable output for a random domain name.
I'm posting it as an example of a recursive anonymous closure:
这绝对不如 Ruby 对应的漂亮,但是,正如 Ted 提到的,这主要是因为
shuffle
方法是Collections
中的静态方法。我正在使用扩展运算符技巧将范围转换为列表:)
This is definitely not as pretty as the Ruby counterpart but, as Ted mentioned, it's mostly because of the fact that
shuffle
method is a static method inCollections
.I am using the spread operator trick to convert the range into a list :)