我正在创建一个工具,将密码转换为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
答案 0 :(得分:1)
错误可能在这里:
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 = {
"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") }
P.S。您的代码还有一些问题,尤其是:
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