有没有办法在 Ruby 中访问符号表中的所有内容?我希望能够序列化或以其他方式保存程序运行的当前状态。为此,我似乎需要能够遍历范围内的所有变量。
最佳答案
我认为他有 perl 背景,他想获取脚本中定义的所有变量并将它们序列化。这样,当他加载文件时,他就会取回它们。 我仍在搜索如何获取变量列表,但将使用 Marshal.dump 进行序列化,并使用 Marshal.load 进行读回。了解如何获取所有已定义变量的列表后,我将编辑帖子。
编辑:找到了!
您可以通过调用这些方法来获取所有变量的列表:
local_variables
global_variables
And if you haven't already got your serialization code , I would suggest something like this:
- create a class or a Struct instance that holds a variable name and the value of the variable and add them in an array :
local_variables.each {|var| my_array << MyVarObject.new(var,eval(var)) } # eval is used to get the value of the variable
and then serialize the array :
data = Marshal.dump(my_array)
File.open("myfile.ser","w") do |file|
file.puts data
end
关于ruby - 你如何访问 Ruby 中的符号表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/503583/