Creating instance variables while looping over a hash

B

blaine

I"m reading in a YAML file using the yaml library in Ruby. My YAML
looks something like this:

config:
value1: Something here
value2: Something else

As I loop from the YAML like:

config["config"].each { |key, value| }

How could I set the key as an instance variable with the value of the
value of the key... resulting in:

@value1 = "Something here"
@value2 = "Something else"

Any thoughts?
 
D

dohzya

Le mercredi 25 juillet 2007 à 21:57 +0900, blaine a écrit :
I"m reading in a YAML file using the yaml library in Ruby. My YAML
looks something like this:

config:
value1: Something here
value2: Something else

As I loop from the YAML like:

config["config"].each { |key, value| }

How could I set the key as an instance variable with the value of the
value of the key... resulting in:

@value1 = "Something here"
@value2 = "Something else"

Any thoughts?

You should play with Object#instance_variable_set(name, value)
 
D

dohzya

Just an example to explain my mind :

---
# some representation of your data
config = {'config' => {'value1' => 'Something here', 'value2' =>
'Something else'}}

class A
def m config
config["config"].each { |key, value|
# attr_accessor key (optional)
self.class.instance_eval {attr_accessor key.to_s}
# @key = value
instance_variable_set "@#{key}", value
}
end
end

# test
a = A.new
a.m config
p a.value2
 
B

blaine

Your example really showed me, thank you so much Etienne. You have
really helped me understand it much better by your example.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top