使用文件';Ruby中的s内容
我的“信息”文件包括以下散列使用文件';Ruby中的s内容,ruby,file,hash,Ruby,File,Hash,我的“信息”文件包括以下散列 student_balances = {"Jane Doe"=>1000, "Jim Doe"=>6200, "John Newman"=>73282, "Leonard Smith"=>3992, "Loe Newton"=>5643, "Eric"=>34234} 我想把这个“信息”文件导入我的主程序,并立即使用它的内容 file_location = "Ruby/account.rb" f = File.open(fi
student_balances = {"Jane Doe"=>1000, "Jim Doe"=>6200, "John Newman"=>73282, "Leonard Smith"=>3992, "Loe Newton"=>5643, "Eric"=>34234}
我想把这个“信息”文件导入我的主程序,并立即使用它的内容
file_location = "Ruby/account.rb"
f = File.open(file_location, "r+")
student_balances.each do |key, value|
puts "#{key} : #{value}"
end
我不知道当输入文件包含以下字符串并且您希望 要在ruby变量中导入字符串,首先必须计算 一串然后可以将变量用作数组
student_balances = nil
DATA.readline.each do | line |
eval line
puts student_balances
end
__END__
student_balances = {"Jane Doe"=>1000, "Jim Doe"=>6200, "John Newman"=>73282, "Leonard Smith"=>3992, "Loe Newton"=>5643, "Eric"=>34234}
我建议以另一种格式(如YAML)存储数据。更易于阅读和书写:
# in balances.yml
"Jane Doe": 1000
"Jim Doe": 6200
"John Newman": 73282
"Leonard Smith": 3992
"Loe Newton": 5643
"Eric": 34234
使用以下命令读取文件:
require 'yaml'
balances = YAML.load_file('balances.yml')
您没有在任何地方使用
f
。。。不要低估你的代码。我以后会使用f
。我想说的是,我想从account.rb导入散列并直接使用它。您的文件是否只包含该散列?是的,作为散列存储在变量student\u balances
中。您真的需要student\u balances
变量吗?这样使用eval真的很危险。@robertodecurnex:这是真的。但这也许能回答问题?@Monk_代码取决于使用的ruby。太好了!这就是我要找的:)为什么它直接作为散列导入?阅读本页()了解YAML文件的语法和格式。它还支持写入文件,例如在您更改余额后:File.open('new_balances.yml','w'){| f | f.write balances.to_yaml}