Maison  >  Questions et réponses  >  le corps du texte

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

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

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

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

伊谢尔伦伊谢尔伦2712 Il y a quelques jours727

répondre à tous(3)je répondrai

  • ringa_lee

    ringa_lee2017-04-22 09:01:12

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

    Ce qui suit est plus efficace :
    o = [('a'..'z'),('A'..'Z')].map{|i| i.to_a} .aplatir ;o = [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten;
    string = (0...50).map{ o[rand(o.length)] }.join;
    string = (0...50).map{ o[rand(o.length)] }.join;

    répondre
    0
  • 巴扎黑

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

    Ajoutez-en un de plus pour l'affiche au choix :
    rand(36 ** n).to_s(36)
    n est la longueur de la chaîne générée

    répondre
    0
  • PHPz

    PHPz2017-04-22 09:01:12

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

    répondre
    0
  • Annulerrépondre