Ruby 生成随机字符串并保存到文件

Ruby 生成随机字符串并保存到文件,ruby,file,random,save,Ruby,File,Random,Save,我一直在用Ruby编写一个简单的程序,生成一个63个字符长的随机字符串,然后将它存储在一个文本文件中。 现在我的代码是: def Password_Generator(length=63) chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a password = '' length.time { |i| password << chars[rand(chars.length)] } aFile = F

我一直在用Ruby编写一个简单的程序,生成一个63个字符长的随机字符串,然后将它存储在一个文本文件中。 现在我的代码是:

def Password_Generator(length=63)
  chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
  password = ''
  length.time { |i| password << chars[rand(chars.length)] }
  aFile = File.new("Generated-Password.txt", "w+")
  aFile.write(password)
  aFile.close
end
首先,在Ruby中,Password_生成器是一个糟糕的方法名,因为常量用于类名。此外,Ruby开发人员更喜欢snake_案例而不是camelCase。对于您的实际问题,它是Ruby 1.9:

def generate_password(length=63)
  chars = [*?a..?z, *?A..?Z, *0..9]
  (1..length).map{ chars.sample }.join
end
我可能会用另一种方法实际写入文件,分离关注点等等。

首先,在Ruby中,Password\u Generator是一个糟糕的方法名,因为常量用于类名。此外,Ruby开发人员更喜欢snake_案例而不是camelCase。对于您的实际问题,它是Ruby 1.9:

def generate_password(length=63)
  chars = [*?a..?z, *?A..?Z, *0..9]
  (1..length).map{ chars.sample }.join
end
require 'securerandom'
def generate_password(length=63)
  # urlsafe_base64 uses lowercase, uppercase, 1-9 and _-. 
  # The latter are removed from the generated string.
  SecureRandom.urlsafe_base64(length).delete('_-')[0, length]
end

File.open('pwd.txt', 'w'){|f| f.puts generate_password}

我可能会用另一种方法实际写入文件,分离关注点等等。

哇,我真的不明白生成随机字符串的方法!从来没见过。你能发布写文件功能吗?谢谢你的快速回答!要写入文件,请使用file.opengenerated password.txt'、'w+'{| w | w.write generate_password}我对它进行了测试,它成功了!非常感谢你们两位的帮助!感谢您的*?一种生成随机数的方法!*在此上下文中是splat运算符[*1..3]=>[1,2,3]?a是一个字符文本,因此我们将显示一系列字符[*?a…?e]=>[a,b,c,d,e]@Jacob向你展示了一种写入文件的方法。很高兴能帮助你。顺便说一句:如果这是你想要的答案,请接受它,让其他人知道它已经得到了充分的回答。这被认为是堆栈溢出的良好实践。哇,我真的不明白生成随机字符串的方法!从来没见过。你能发布写文件功能吗?谢谢你的快速回答!要写入文件,请使用file.opengenerated password.txt'、'w+'{| w | w.write generate_password}我对它进行了测试,它成功了!非常感谢你们两位的帮助!感谢您的*?一种生成随机数的方法!*在此上下文中是splat运算符[*1..3]=>[1,2,3]?a是一个字符文本,因此我们将显示一系列字符[*?a…?e]=>[a,b,c,d,e]@Jacob向你展示了一种写入文件的方法。很高兴能帮助你。顺便说一句:如果这是你想要的答案,请接受它,让其他人知道它已经得到了充分的回答。在这里,这被认为是关于堆栈溢出的良好实践。
require 'securerandom'
def generate_password(length=63)
  # urlsafe_base64 uses lowercase, uppercase, 1-9 and _-. 
  # The latter are removed from the generated string.
  SecureRandom.urlsafe_base64(length).delete('_-')[0, length]
end

File.open('pwd.txt', 'w'){|f| f.puts generate_password}