Convert

Hello

I wonder if there is a simple way to convert all keys in a Hash to
member variables in a Class without knowing the key names in the Hash
beforehand.

example
  MyHash["ada"] = "yes"
  MyHash["beda"] = "no"
  MyHash["foo"] = "bar"
  ...
  ...
  ...
  MyHash["whatever"]='whatever'

can be accessed via the point operator

  myClass.ada
  myClass.beda
  myClass.foo
  ...
  ...
  ...
  myClass.whatever

/Joakim

···

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

Joakim Oman wrote:

Hello

I wonder if there is a simple way to convert all keys in a Hash to member variables in a Class without knowing the key names in the Hash beforehand.

   vars = {:foo => 101, :bar => 42, :baz => 1337}
   vars.each do |name, value|
     SomeClass.instance_variable_set("@#{name}", value)
   end

You could also use an OpenStruct.

Cheers,
Daniel

Daniel Schierbeck wrote:

Joakim Oman wrote:

Hello

I wonder if there is a simple way to convert all keys in a Hash to
member variables in a Class without knowing the key names in the Hash
beforehand.

  vars = {:foo => 101, :bar => 42, :baz => 1337}
  vars.each do |name, value|
    SomeClass.instance_variable_set("@#{name}", value)
  end

You could also use an OpenStruct.

That won't work, because it doesn't create accessors.

This has been discussed recently a couple of times.

  Ruby Quiz - Hash to OpenStruct (#81)

Also, the simple answer is this:

  require 'ostruct'
  obj = OpenStruct.new(hash)

Cheers,
Dave

Thanks

/Joakim

···

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

Dave Burt wrote:

Daniel Schierbeck wrote:

Joakim Oman wrote:

Hello

I wonder if there is a simple way to convert all keys in a Hash to
member variables in a Class without knowing the key names in the Hash
beforehand.

  vars = {:foo => 101, :bar => 42, :baz => 1337}
  vars.each do |name, value|
    SomeClass.instance_variable_set("@#{name}", value)
  end

You could also use an OpenStruct.

That won't work, because it doesn't create accessors.

Ahh, didn't see the last part of the post!

(Damn these trigger-happy fingers of mine!)

Cheers,
Daniel