生成随机字符串并保存到文件
我一直在用 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
I'm stuck doing so simple program in Ruby that would generate a 63 characters long random string and then storing it in a text file.
For now my code is :
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,
Password_Generator
在 Ruby 中是一个不好的方法名称,因为常量用于类名称。此外,Ruby 开发人员更喜欢 Snake_Case 而不是 CamelCase。对于你的实际问题(这是 Ruby 1.9):我可能会用不同的方法实际写入文件,关注点分离等等。
First off,
Password_Generator
is a bad method name in Ruby, since constants are used for class names. Also Ruby developers prefer snake_case over camelCase. For your actual question (it's Ruby 1.9):I'd probably do the actual writing to a file in a different method, separation of concerns and all that.