Home  >  Q&A  >  body text

字符串函数 - Ruby 中如何生成一个随机字符串?

需要得到一个大小写混合的字符串[a,A-Z,z],目前用的方法是

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

感觉还是不好,而且再加混合数字的串就不会了。不知道有没有更好的方法,烦请详细指点!

伊谢尔伦伊谢尔伦2761 days ago760

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-22 09:01:12

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

    The following is more efficient:
    o = [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten;
    string = (0...50).map{ o[rand(o.length)] }.join;

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-22 09:01:12

    Add one more for the poster to choose from:
    rand(36 ** n).to_s(36)
    n is the length of the generated string

    reply
    0
  • PHPz

    PHPz2017-04-22 09:01:12

    [*('a'..'z'),*('A'..'Z'),*(0..9)].shuffle[0..9].join

    reply
    0
  • Cancelreply