我正在创建一个工具,将密码转换为YAML文件中的MD5哈希,在运行我的程序时,我收到了错误:
md5.rb:20:in `encrypt_md5': undefined method `[]=' for nil:NilClass (NoMethodError)
from main.rb:12:in `main'
from main.rb:40:in `<main>'
从这个方法:
def encrypt_md5
hash = load_file
hash[:users][:"#{prompt('Enter username')}"] =
{password: prompt("Enter password")}
save_file(hash)
exit unless again?('encrypt md5')
end
#Digest::MD5 hasn't been implemented yet
我不完全确定是什么导致了nil:NilClass NoMethodError
,有人能向我解释一下这意味着什么,并告诉我需要改变什么才能使其工作吗。。
Main.rb来源:
require_relative 'md5.rb'
def main
puts <<-END.gsub(/^s*>/, '')
>
>To load information type "L" to quit system type "Q"
>
END
input = gets.chomp.upcase
case input
when "L"
encrypt_md5
when "Q"
exit_system
else
exit_lock
end
end
def exit_system
puts "Exiting..."
exit
end
def exit_lock #Not finished, will lock user out of program
puts "Locked out, please contact system administrator"
exit
end
def again? #Not complete
puts "Encrypt more?"
input = gets.chomp
return input =~ /yes/i
end
def prompt( message )
puts message
gets.chomp
end
main
md5.rb来源:
require 'yaml'
require 'digest'
private
def load_file
File.exist?('info.yml') ? YAML.load_file('info.yml') : {passwords: {}}
end
def read_file
File.read('info.yml')
end
def save_file
File.open('info.yml', 'w') { |s| s.write('info.yml')}
end
def encrypt_md5
hash = load_file
hash[:users][:"#{prompt('Enter username')}"] =
{password: prompt("Enter password")}
save_file(hash)
exit unless again?('encrypt md5')
end
错误可能在这里:
hash = load_file
hash[:users][:"#{prompt('Enter username')}"] =
{ password: prompt("Enter password") }
您在hash[:users]
上调用[]=
方法,但hash[:users]
是nil
。由于你没有发布info.yml
的内容,我只能猜测你有一个像这样的YAML文件:
users:
some_user:
password: foobar
another_user:
password: abcxyz
# ...
当你对该文件执行YAML.load_file
时,你会得到这个Hash:
hash = {
"users" => {
"some_user" => { "password" => "foobar" },
"another_user" => { "password" => "abcxyz" },
# ...
}
}
这样,hash[:users]
就是nil
,因为没有:users
密钥,只有"users"
密钥。虽然你可以跳过一些障碍,把你的钥匙变成符号,但在任何地方使用字符串键都会容易得多:
hash = load_file
hash["users"][prompt('Enter username')] =
{ "password" => prompt("Enter password") }
附言:你的代码还有一些问题,特别是在这里:
def save_file
File.open('info.yml', 'w') { |s| s.write('info.yml')}
end
首先,您调用save_file(hash)
,但save_file
方法不接受任何参数。这将引发ArgumentError。其次,此方法中的代码所做的是打开文件info.yml
,然后将字符串"info.yml"
写入该文件。你可能想要的是这样的东西:
def save_file(hash)
File.open('info.yml', 'w') {|f| f.write(hash.to_yaml) }
end