我的“信息”文件包含以下哈希值。
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
我无法弄清楚如何。
答案 0 :(得分:1)
我建议将数据存储为其他格式,如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')
答案 1 :(得分:0)
当输入文件包含以下字符串时,您会喜欢 要在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}