# Creating instance variables while looping over a hash

**URL:** <https://www.ruby-forum.com/t/creating-instance-variables-while-looping-over-a-hash/110314>\
**Category:** Rails\
**Created:** [July 25, 2007, 8:41am UTC](https://www.ruby-forum.com/t/creating-instance-variables-while-looping-over-a-hash/110314 "2007-07-25T08:41:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![blaine](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/51bf81/32.png) [@blaine](https://www.ruby-forum.com/u/blaine)\
**Post date:** [July 25, 2007, 8:41am UTC](https://www.ruby-forum.com/t/creating-instance-variables-while-looping-over-a-hash/110314/1 "2007-07-25T08:41:29Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![blaine](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/51bf81/32.png) [@blaine](https://www.ruby-forum.com/u/blaine)\
**Post date:** [July 25, 2007, 8:07pm UTC](https://www.ruby-forum.com/t/creating-instance-variables-while-looping-over-a-hash/110314/2 "2007-07-25T20:07:41Z")

</div>

config[“config”].each {|key,value| instance\_variable\_set("@#{key}",  
value)};

you’ll probably want to remove spaces and convert odd chars in the key  
to make sure it follows instance variable naming guidelines.

Adam

---

<div class="post-metadata">

**Author:** ![blaine](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/51bf81/32.png) [@blaine](https://www.ruby-forum.com/u/blaine)\
**Post date:** [July 26, 2007, 7:15am UTC](https://www.ruby-forum.com/t/creating-instance-variables-while-looping-over-a-hash/110314/3 "2007-07-26T07:15:54Z")

</div>

Thank you so much Adam.

Tim
