Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top