如何在Ruby中生成随机字符串 [英] How to generate a random string in Ruby

查看:195
本文介绍了如何在Ruby中生成随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为"A" .."Z"生成一个8个字符的伪随机大写字符串:

I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":

value = ""; 8.times{value  << (65 + rand(25)).chr}

,但它看起来并不整洁,并且由于它不是单个语句,因此不能作为参数传递.为了获得大小写混合的字符串"a" .."z"加"A" .."Z",我将其更改为:

but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:

value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}

但它看起来像垃圾.

有人有更好的方法吗?

推荐答案

(0...8).map { (65 + rand(26)).chr }.join

我花太多时间打高尔夫球.

I spend too much time golfing.

(0...50).map { ('a'..'z').to_a[rand(26)] }.join

最后一个更加令人困惑,但更加灵活并且浪费了更少的周期:

And a last one that's even more confusing, but more flexible and wastes fewer cycles:

o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
string = (0...50).map { o[rand(o.length)] }.join

这篇关于如何在Ruby中生成随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆