【问题标题】:How can I generate random mixed letters and numbers in Ruby如何在 Ruby 中生成随机混合字母和数字
【发布时间】:2013-03-25 07:48:17
【问题描述】:

到目前为止,我有以下代码,它只生成字母。我希望同时获得字母和数字

#Generate random 8 digit number and output to file
    output = File.new("C:/Users/%user%/Desktop/Strings.txt", "w")

    i = 0
     while i < 500
        randomer = (0...8).map{65.+(rand(26)).chr}.join
        output << randomer
        output << "\n"
        i = i+1
     end

    output.close

【问题讨论】:

标签: ruby


【解决方案1】:

这个怎么样:

def random_tuple(length)
    letters_and_numbers = "abcdefghijklmnopqrstuvwxyz0123456789"
    answer = ""
    length.times { |i| answer << letters_and_numbers[rand(36)] }
    answer
end

output = ""
500.times { |i| output << random_tuple(8) + "\n" }

您也可以让函数追加换行符,但我认为这种方式更通用。

【讨论】:

  • 有没有办法在其中添加一个新行,以便每个值出现在单独的行上。
  • 这会将每个字符添加到新行,但我需要将每个 8 位值放在单独的行上。
  • 工作正常,但您必须删除 output="" 才能正常工作。
【解决方案2】:
(('a'..'z').to_a + ('0'..'9').to_a).sample( 8 ).join

这个随机的,但不会重复使用任何数字/字母,所以它不会涵盖所有可能的字符串。

【讨论】:

  • 不重复使用任何数字/字母!哇!
  • 这给了我一个语法错误,期望 keyword_end randomer = ('a'..'z').to_a + ('0'..'9').to_a).sample(length )。加入^
  • @Ninja2k。笔误,现已修正。谢谢你告诉我
  • 它并没有使用所有可能的组合。对于您的使用,当您有几十个产品时,这对于 8 个字母的代码将开始很重要(当您有 613 个产品时,其中两个具有相同代码的可能性为 50/50,至少除非您清除重复!)其他海报可以为您提供多达几万个具有相同 8 个字母的产品。 . .
【解决方案3】:

所有数字和字母均以 36 为基数:

max = 36**8
500.times.map{ rand(max).to_s(36).rjust(8,'0') } #rjust pads short strings with '0'

【讨论】:

    【解决方案4】:

    使用SecureRandom.hex(10)他生成0-9和a-f中的字母和数字

    SecureRandom.base64.delete('/+=')[0, 8]
    

    http://www.ruby-doc.org/stdlib-1.9.3/libdoc/securerandom/rdoc/SecureRandom.html

    【讨论】:

      【解决方案5】:

      你可以这样做

      i = 0
      while i < 500
          randomer = (1..8).map { (('a'..'z').to_a + ('0'..'9').to_a)[rand(36)] }.join
          output << randomer
          output << "\n"
          i = i+1
      end
      
      output.close
      

      享受吧。

      【讨论】:

      • 如何将其整合到我当前的公式中?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2011-01-29
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多