# Automatically setting attributes

**URL:** <https://rubytalk.org/t/automatically-setting-attributes/12804>\
**Category:** ruby-talk\
**Created:** [29 July 2004 02:13 UTC](https://rubytalk.org/t/automatically-setting-attributes/12804 "2004-07-29T02:13:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mehr\_Assaph\_Assaph](https://avatars.discourse-cdn.com/v4/letter/m/77aa72/32.png) [@Mehr\_Assaph\_Assaph](https://rubytalk.org/u/Mehr_Assaph_Assaph)\
**Post date:** [29 July 2004 02:13 UTC](https://rubytalk.org/t/automatically-setting-attributes/12804/1 "2004-07-29T02:13:44Z")

</div>

> How can I do something like the following:

> class Foo  
> &nbsp;&nbsp;&nbsp;attr\_accessor :goo, :moo  
> &nbsp;&nbsp;&nbsp;def initalize  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@attr.each { | attrib| attrib = 0 }

&nbsp;&nbsp;&nbsp;&nbsp;[:goo,:moo].each { |sym| send "#{sym}=", 0 }  
or:  
&nbsp;&nbsp;&nbsp;&nbsp;[:goo,:moo].each { |sym| instance\_eval "@#{sym} ||= 0" }

> &nbsp;&nbsp;&nbsp;end  
> end

You have to specify the variable names. Ruby only creates an instance of  
the variable once it's accessed.

---

<div class="post-metadata">

**Author:** ![David\_A\_Black3](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@David\_A\_Black3](https://rubytalk.org/u/David_A_Black3)\
**Post date:** [29 July 2004 02:38 UTC](https://rubytalk.org/t/automatically-setting-attributes/12804/2 "2004-07-29T02:38:59Z")

</div>

Hi --

> **···**
>
> On Thu, 29 Jul 2004, Mehr, Assaph (Assaph) wrote:
> 
> > \> How can I do something like the following:
> > 
> > \> class Foo  
> > \> attr\_accessor :goo, :moo  
> > \> def initalize  
> > \> @attr.each { | attrib| attrib = 0 }
> > 
> > &nbsp;&nbsp;&nbsp;&nbsp;[:goo,:moo].each { |sym| send "#{sym}=", 0 }  
> > or:  
> > &nbsp;&nbsp;&nbsp;&nbsp;[:goo,:moo].each { |sym| instance\_eval "@#{sym} ||= 0" }
> > 
> > \> end  
> > \> end
> 
> You could also use: instance\_variable\_set("@#{sym}",0)  
> (which might be more self-documenting).
> 
> David
> 
> --  
> David A. Black  
> dblack@wobblini.net
