你如何访问 Ruby 中的符号表? [英] How do you access the symbol table in Ruby?

查看:47
本文介绍了你如何访问 Ruby 中的符号表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Ruby 中访问符号表中的所有内容?我希望能够序列化或以其他方式保存程序运行的当前状态.为此,我似乎需要能够遍历范围内的所有变量.

解决方案

我认为他来自 perl 背景,并且他想获取脚本中定义的所有变量并将它们序列化.这样,当他加载文件时,他会将它们取回.我仍在寻找如何获取变量列表,但将使用 Marshal.dump 进行序列化,并使用 Marshal.load 进行读取.一旦我找到如何获取所有已定义变量的列表,我将编辑该帖子.

找到了!

您可以通过调用这些方法获取所有变量的列表:

<前>local_variablesglobal_variables

如果您还没有获得序列化代码,我建议您这样做:

  • 创建一个类或一个包含变量名和变量值的 Struct 实例,并将它们添加到数组中:
<前><代码>local_variables.each {|var|my_array << MyVarObject.new(var,eval(var)) } # eval 用于获取变量的值

然后序列化数组:

<预><代码>数据 = Marshal.dump(my_array)File.open("myfile.ser","w") do |file|file.puts 数据结束

Is there a way to access everything in the symbol table in Ruby? I want to be able to serialize or otherwise save the current state of a run of a program. To do this, it seems I need to be able to iterate over all the variables in scope.

解决方案

I think he comes from a perl background , and that he would like to obtain all the variables defined in a script and serialize them . This way , when he'll load the file , he'll get them back . I'm still searching about how to get a list of the variables , but serialization will be made using Marshal.dump and reading them back will be made with Marshal.load . I'll edit the post once I find out how to get a list of all defined variables .

EDIT : found it!

You can get a list of all variables by calling these methods :

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 中的符号表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆