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

发布于 2024-12-13 21:06:59 字数 372 浏览 5 评论 0原文

我一直在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

方觉久 2024-12-20 21:06:59

首先,Password_Generator 在 Ruby 中是一个不好的方法名称,因为常量用于类名称。此外,Ruby 开发人员更喜欢 Snake_Case 而不是 CamelCase。对于你的实际问题(这是 Ruby 1.9):

def generate_password(length=63)
  chars = [*?a..?z, *?A..?Z, *0..9]
  (1..length).map{ chars.sample }.join
end

我可能会用不同的方法实际写入文件,关注点分离等等。

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):

def generate_password(length=63)
  chars = [*?a..?z, *?A..?Z, *0..9]
  (1..length).map{ chars.sample }.join
end

I'd probably do the actual writing to a file in a different method, separation of concerns and all that.

无人问我粥可暖 2024-12-20 21:06:59
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}
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}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文