On 16.11.2008 10:46, Adam Akhtar wrote:
> Tried my best to make this title as informative as possible but its
> ended up a bit cryptic.
> 
> Say I have a class Record which represents records in a database and a
> particular object  has these instance variables
> 
> @a = 1
> @b = 2
> @c = 3
> 
> 
> Id like to be able to create a hash that has the varible names i.e.
> a,b,c as keys and then their values as the hash values.
> 
> 
> e.g. {a=>1, b=>2, c=>3}
> 
> HOWEVER i would like this to be done dynamically so that if I add or
> remove variables to my class definition the conversion method will
> include these without me having to hard code them in the conversion
> function.
> 
> 
> Is this possible and if so what topic would this come under in a book?
> Any tips or code snippets would be greatly appreciated.

Depends on what you want to do with the Hash but Struct may help you:

irb(main):001:0> S = Struct.new :a, :b, :c
=> S
irb(main):002:0> s = S.new 1,2,3
=> #<struct S a=1, b=2, c=3>
irb(main):003:0> s[:a]
=> 1
irb(main):004:0> s[:b]
=> 2
irb(main):005:0> s[:c]=100
=> 100
irb(main):006:0> s
=> #<struct S a=1, b=2, c=100>
irb(main):007:0>

If you want to add additional methods to the Struct you can do

S = Struct.new :a, :b, :c do
   def some_method
     (a + b) * c
   end
end

Kind regards

	robert