Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access the symbol table in Ruby?

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.

like image 685
Jonathan Tran Avatar asked Feb 02 '09 15:02

Jonathan Tran


People also ask

How do I create a symbol in Ruby?

Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.

What is the symbol of Ruby?

Many cultures have long considered ruby a stone of kings. Not surprisingly, ruby symbolism and lore have many associations with power and wealth. Possessing a ruby purportedly benefited and protected the owner's estates and assisted in the accumulation of wealth.

How do I convert a symbol to a string in Ruby?

Converting between symbols to strings is easy - use the . to_s method. Converting string to symbols is equally easy - use the . to_sym method.


1 Answers

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
like image 134
Geo Avatar answered Sep 28 '22 02:09

Geo