# Dynamically added methods

**URL:** <https://rubytalk.org/t/dynamically-added-methods/20099>\
**Category:** ruby-talk\
**Created:** [11 August 2005 17:48 UTC](https://rubytalk.org/t/dynamically-added-methods/20099 "2005-08-11T17:48:10Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yann\_Klis](https://avatars.discourse-cdn.com/v4/letter/y/a8b319/32.png) [@Yann\_Klis](https://rubytalk.org/u/Yann_Klis)\
**Post date:** [11 August 2005 17:48 UTC](https://rubytalk.org/t/dynamically-added-methods/20099/1 "2005-08-11T17:48:10Z")

</div>

Hi all,

I'm pretty new to ruby so I will ask some dumb questions, sorry if it's  
not the right place to ask 🙂

I'd like to add some methods dynamically to one of my object.  
I understand that with "method\_missing" I can "emulate" this behaviour.

However, imagine I have an hash table. The key would be the attributes  
of my object, and the keys their value. How could I add dynamically  
accessors for those attributes/keys ?

Thanks in advance,

> **···**
>
> ++
> 
> yk

---

<div class="post-metadata">

**Author:** ![Austin\_Ziegler5](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/austin_ziegler5/32/1985_2.png) [@Austin\_Ziegler5](https://rubytalk.org/u/Austin_Ziegler5)\
**Post date:** [11 August 2005 18:48 UTC](https://rubytalk.org/t/dynamically-added-methods/20099/2 "2005-08-11T18:48:22Z")

</div>

Use OpenStruct.

&nbsp;&nbsp;require 'ostruct'  
&nbsp;&nbsp;os = OpenStruct.new  
&nbsp;&nbsp;os.foo = "hello"  
&nbsp;&nbsp;os.bar = "world"  
&nbsp;&nbsp;puts "#{os.foo}, #{os.bar}"

-austin

> **···**
>
> On 8/11/05, Yann Klis \<strass@strasslab.net\> wrote:
> 
> > Hi all,
> > 
> > I'm pretty new to ruby so I will ask some dumb questions, sorry if it's  
> > not the right place to ask 🙂
> > 
> > I'd like to add some methods dynamically to one of my object.  
> > I understand that with "method\_missing" I can "emulate" this behaviour.
> > 
> > However, imagine I have an hash table. The key would be the attributes  
> > of my object, and the keys their value. How could I add dynamically  
> > accessors for those attributes/keys ?
> 
> --  
> Austin Ziegler \* halostatue@gmail.com  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\* Alternate: austin@halostatue.ca

---

<div class="post-metadata">

**Author:** ![Shalev\_NessAiver](https://avatars.discourse-cdn.com/v4/letter/s/58956e/32.png) [@Shalev\_NessAiver](https://rubytalk.org/u/Shalev_NessAiver)\
**Post date:** [11 August 2005 20:29 UTC](https://rubytalk.org/t/dynamically-added-methods/20099/3 "2005-08-11T20:29:35Z")

</div>

To clarify - you want to be able to do something like this:

class YourObject

&nbsp;&nbsp;&nbsp;def initialize  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@myhash = {'key1' =\> 'value1', 'key2' =\> 'value2', 'key3' =\> 'value3'}  
&nbsp;&nbsp;&nbsp;end

end

YourObject.new.key1 # Returns 'value1'  
YourObject.new.key2 # Returns 'value2'

.... like that?

-Shalev

> **···**
>
> On Aug 11, 2005, at 1:48 PM, Yann Klis wrote:
> 
> > Hi all,
> > 
> > I'm pretty new to ruby so I will ask some dumb questions, sorry if it's  
> > not the right place to ask 🙂
> > 
> > I'd like to add some methods dynamically to one of my object.  
> > I understand that with "method\_missing" I can "emulate" this behaviour.
> > 
> > However, imagine I have an hash table. The key would be the attributes  
> > of my object, and the keys their value. How could I add dynamically  
> > accessors for those attributes/keys ?
> > 
> > Thanks in advance,
> > 
> > ++
> > 
> > yk

---

<div class="post-metadata">

**Author:** ![Yann\_Klis](https://avatars.discourse-cdn.com/v4/letter/y/a8b319/32.png) [@Yann\_Klis](https://rubytalk.org/u/Yann_Klis)\
**Post date:** [11 August 2005 21:31 UTC](https://rubytalk.org/t/dynamically-added-methods/20099/4 "2005-08-11T21:31:52Z")

</div>

In fact, I'd like to mimic the behaviour of ActiveRecord.

If I have something like this:

class Base

&nbsp;&nbsp;def initialize(attributes)  
&nbsp;&nbsp;&nbsp;&nbsp;#do something clever with attributes  
&nbsp;&nbsp;end

end

class MyObject \< Base  
end

I'd like to be able to do that:

object = MyObject.new({"attribute1" =\> "value1", "attribute2" =\>  
"value2"})  
val = object.attribute1

Thanks,

yk

> **···**
>
> Le vendredi 12 août 2005 à 05:29 +0900, Shalev NessAiver a écrit :
> 
> > To clarify - you want to be able to do something like this:
> > 
> > class YourObject
> > 
> > &nbsp;&nbsp;&nbsp;def initialize  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@myhash = {'key1' =\> 'value1', 'key2' =\> 'value2', 'key3' =\>  
> > 'value3'}  
> > &nbsp;&nbsp;&nbsp;end
> > 
> > end
> > 
> > YourObject.new.key1 # Returns 'value1'  
> > YourObject.new.key2 # Returns 'value2'
> > 
> > .... like that?
> > 
> > -Shalev
> > 
> > On Aug 11, 2005, at 1:48 PM, Yann Klis wrote:
> > 
> > \> Hi all,  
> > \>  
> > \> I'm pretty new to ruby so I will ask some dumb questions, sorry if  
> > \> it's  
> > \> not the right place to ask 🙂  
> > \>  
> > \> I'd like to add some methods dynamically to one of my object.  
> > \> I understand that with "method\_missing" I can "emulate" this  
> > \> behaviour.  
> > \>  
> > \> However, imagine I have an hash table. The key would be the attributes  
> > \> of my object, and the keys their value. How could I add dynamically  
> > \> accessors for those attributes/keys ?  
> > \>  
> > \> Thanks in advance,  
> > \>  
> > \> ++  
> > \>  
> > \> yk  
> > \>  
> > \>  
> > \>

---

<div class="post-metadata">

**Author:** ![Zach\_Dennis1](https://avatars.discourse-cdn.com/v4/letter/z/ea5d25/32.png) [@Zach\_Dennis1](https://rubytalk.org/u/Zach_Dennis1)\
**Post date:** [12 August 2005 03:19 UTC](https://rubytalk.org/t/dynamically-added-methods/20099/5 "2005-08-12T03:19:54Z")

</div>

Yann Klis wrote:

> In fact, I'd like to mimic the behaviour of ActiveRecord.
> 
> If I have something like this:
> 
> class Base
> 
> &nbsp;&nbsp;def initialize(attributes)  
> &nbsp;&nbsp;&nbsp;&nbsp;#do something clever with attributes  
> &nbsp;&nbsp;end
> 
> end
> 
> class MyObject \< Base  
> end
> 
> I'd like to be able to do that:
> 
> object = MyObject.new({"attribute1" =\> "value1", "attribute2" =\>  
> "value2"})  
> val = object.attribute1

To create methods on the class itself so all instances of that class get the method you can do:

class A  
&nbsp;&nbsp;&nbsp;def initialize( args=nil )  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if args.is\_a? Hash  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;args.each { |key,val| self.class.send( :define\_method, key, proc { val } ) }  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;end  
end

a = A.new( :zzz =\> "testing" )  
puts a.zzz  
b = A.new  
puts b.zzz

To create methods on the instance you have created only you can do:

class A  
&nbsp;&nbsp;&nbsp;def initialize( args=nil )  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if args.is\_a? Hash  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s = class \<\< self; self; end  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;args.each { |key,val| s.send( :define\_method, key, proc { val } ) }  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;end   
end

a = A.new( :zzz =\> "testing" )  
puts a.zzz  
b = A.new  
puts b.zzz #this will throw an error,because method zzz doesn't exist on this instance

Note, that I think the second example above is bad design. We are relying on an instance of A to give the class A extra methods for all instances. We should instead rely on a singleton method for class A to handle this task. (keep reading)

The above two solutions don't take into consideration if a method already exists though, so you could easily overwrite an existing method. Another way to do this is by overriding the method missing for your class which won't override existing methods. The below will handle things for instances only, like the first example:

class A  
&nbsp;&nbsp;&nbsp;def initialize( args={} )  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@args = args if args.is\_a? Hash  
&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;def method\_missing( method )  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@args[method] || super  
&nbsp;&nbsp;&nbsp;end  
end

puts A.new( :a =\> "z" ) # prints out "z"  
A.new.a #throws an error because :a wasn't passed in to this object

And you can alter that to add methods for the class also so all instances get the methods, although above in the second example I think we used bad designed. So here we fix it by using a singleton method 'add\_attributes':

class A  
&nbsp;&nbsp;&nbsp;def self.add\_attributes( attributes )  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@@attributes = attributes  
&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;def initialize( args={} )  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@args = args if args.is\_a? Hash  
&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;def method\_missing( method )  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@@attributes[method] || super  
&nbsp;&nbsp;&nbsp;end  
end

A.add\_attributes( :attr1 =\> "attribute 1", :attr2 =\> "attribute 2" )  
puts A.new.attr1  
puts A.new.attr2

I hope this helps!

Zach

---

<div class="post-metadata">

**Author:** ![Robert](https://avatars.discourse-cdn.com/v4/letter/r/e95f7d/32.png) [@Robert](https://rubytalk.org/u/Robert)\
**Post date:** [12 August 2005 07:56 UTC](https://rubytalk.org/t/dynamically-added-methods/20099/6 "2005-08-12T07:56:11Z")

</div>

Yann Klis wrote:

> In fact, I'd like to mimic the behaviour of ActiveRecord.
> 
> If I have something like this:
> 
> class Base
> 
> &nbsp;&nbsp;def initialize(attributes)  
> &nbsp;&nbsp;&nbsp;&nbsp;#do something clever with attributes  
> &nbsp;&nbsp;end
> 
> end
> 
> class MyObject \< Base  
> end
> 
> I'd like to be able to do that:
> 
> object = MyObject.new({"attribute1" =\> "value1", "attribute2" =\>  
> "value2"})  
> val = object.attribute1

As others have pointed out already, use OpenStruct:

09:51:10 [robert.klemme]: irbs

> > require 'ostruct'

=\> true

> > object = OpenStruct.new( "attribute1" =\> "value1", "attribute2" =\>

?\> "value2")  
=\> \<OpenStruct attribute1="value1" attribute2="value2"\>

> > object.attribute1

=\> "value1"

> > object.attribute2

=\> "value2"

If you need inheritance, you can do

class MyObject \< OpenStruct  
end

That's it.

If you need additional initialization, you'll have to do

class MyObject \< OpenStruct  
&nbsp;&nbsp;def initialize(attrs)  
&nbsp;&nbsp;&nbsp;&nbsp;super(attrs)  
&nbsp;&nbsp;&nbsp;&nbsp;# do more init  
&nbsp;&nbsp;end  
end

Kind regards

&nbsp;&nbsp;&nbsp;&nbsp;robert

---

<div class="post-metadata">

**Author:** ![Zach\_Dennis1](https://avatars.discourse-cdn.com/v4/letter/z/ea5d25/32.png) [@Zach\_Dennis1](https://rubytalk.org/u/Zach_Dennis1)\
**Post date:** [12 August 2005 11:49 UTC](https://rubytalk.org/t/dynamically-added-methods/20099/7 "2005-08-12T11:49:31Z")

</div>

Robert Klemme wrote:

> As others have pointed out already, use OpenStruct:

OpenStruct uses the method\_missing magic as pointed out in my last post, so you know now how it does what it does. Refer to ostruct.rb for more implementation details. =)

Zach
