Dynamic creation of variables

Hi everyone!
I am building a interactive shell for chemistry related tasks and am
stuck.
The program loads all the elements of the periodic table and there
properties, into an array of objects.

Eg:

elements[0] is the element hydrogen.
puts elements[0].name #=> "hydrogen"
puts elements[0].mass #=> 1.0079
puts elements[0].symbol #=> "H"

I am also making them available by the symbol as follows

@elements.each do |e|
                instance_variable_set("@" + e.symbol, e)
        end

thus:

puts elements[0].name #=> "hydrogen"
puts @H.name #=> "hydrogen"

But i would prefer it if the elements were loaded up as normal variables
without the '@' in front.

is this possible?

Thanks in advance, Tom

···

--
Posted via http://www.ruby-forum.com/.

puts elements[0].name #=> "hydrogen"
puts @H.name #=> "hydrogen"

But i would prefer it if the elements were loaded up as normal variables
without the '@' in front.

I would recommend making a module, then setting module constants for your element symbols to be mapped to objects. Here is a sample I threw together:

module Chemistry
class Element
attr_reader :name
attr_reader :mass
attr_reader :symbol

    def initialize\(name,mass,symbol\)
        @name = name
        @mass = mass
        @symbol = symbol
    end
end

end

elements = [
Chemistry::Element.new("hydrogen", 1.0079, "H"),
Chemistry::Element.new("lithium", 6.941, "Li")
]

elements.each do |element|
Chemistry.const_set(element.symbol, element)
end

include Chemistry
puts Li.name

Please note the include Chemistry which makes the "Li.name" access possible. This has the advantage of being able to use these constants in other scripts where someone might want to use the H constant for a different purpose, then they can access it like this:

Chemistry::Li.name

Regards,
Chris White
Twitter: @cwgem

Thanks for the quick reply!

This solution is very elegant, especially the way the variables are
kept seperated in the module.

···

--
Posted via http://www.ruby-forum.com/.