How do you access the symbol table in Ruby?

不想你离开。 提交于 2019-12-05 23:17:26

问题


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.


回答1:


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 &lt&lt 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



回答2:


If I have understood your question properly - that you would like to see all the symbols in your program then the following should do the trick:

puts Symbol.all_symbols.inspect

The “all_symbols” class method will return an Array of every Symbol currently in the program.




回答3:


I don't believe there is, but you could always use marshall dump/load.



来源:https://stackoverflow.com/questions/503583/how-do-you-access-the-symbol-table-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!