好的,我正在尝试编写一个包含两个字符串的简单对象,一个是“用户密码”,另一个是“目标密码”,如果您想在远程服务器上编写密码更改脚本,则需要这样做sudo(第一个密码是执行sudo命令,“目标密码”将是密码应重置的字符串。
我希望一次性提示用户输入第一个密码,然后用户将有五次尝试输入第二个密码字符串并准确重复。我想出的,下面的代码似乎不起作用。有什么想法吗?
require 'pp'
require 'RubyGems'
require 'highline/import' #gem install highline
class Authorization
attr_reader :user_password , :target_password
pass_code = lambda {
first_attempt = ask("Enter target password: "){ |q| q.echo = '*' }
second_attempt = ask("Re-enter password to verify"){ |q| q.echo = '*'}
}
### So we need some sort of recursive loop
def initialize(target_pass=false)
@user_password = ask("Enter your admin password: ") { |q| q.echo = '*' }
if target_pass
count = 1
while n < 6
pass_code
if first_attempt == second_attempt
@target_password = first_attempt
return
else
count += 1
end
end
end
end
end
my_pass = Authorization.new(true)
pp "pass" , my_pass
答案 0 :(得分:2)
我看到了几个问题
require "rubygems"
(不是RubyGems)尝试这样的事情。
require "highline/import"
class Authorization
attr_accessor :user_password, :target_password
def prompt(prompt_for_target = false)
self.user_password = ask_for_password("Enter your admin password")
return unless prompt_for_target
5.times do
password = ask_for_password("Enter target password")
confirmation = ask_for_password("Re-enter password to verify")
if password == confirmation
self.target_password = password
return
end
end
end
private
def ask_for_password(message)
ask("#{message}: ") { |q| q.echo = '*' }
end
end
auth = Authorization.new
auth.prompt(true)
puts auth.user_password
puts auth.target_password
答案 1 :(得分:1)
非常简单,与Ryan的解决方案类似:
require 'highline/import' #gem install highline
class Authorization
attr_reader :admin_password, :target_password
def initialize
@admin_password = ask_for_password("Enter your admin password: ")
5.times do
@target_password = ask_for_password("Enter target password: ")
verify_target_pass = ask_for_password("Re-enter password to verify: ")
break if @target_password == verify_target_pass
@target_password = nil
end
end
private
def ask_for_password(message)
ask(message) {|q| q.echo = "*"}
end
end
my_pass = Authorization.new
puts "Administrator's password is: #{my_pass.admin_password}"
puts "Target password is: #{my_pass.target_password}"
答案 2 :(得分:1)
首先,谢谢大家的答案。这是我的第一个问题,不幸的是,它出现了一点点乱码,但你们所有人似乎都非常了解它。
恕我直言,我试图做的是递归,但我不确定这是讨论的最佳位置。我正在使用Ruby 1.8.7,我可能应该在帖子开头提到它。 Ryan的解决方案有效,但只有当我拿出对“self”的引用并在实例变量中替换时:
@user_password = ask_for_password("Enter your admin password") #instead of
self.user_password = ask_for_password("Enter your admin password")
对于Ruby 1.9来说,这可能不是必需的,但它确实具有使prostosuper几乎与Ryan相同的优势。
再一次,谢谢大家!这是一个伟大的“让我的脚湿”的经历。
答案 3 :(得分:0)