# Dynamically Create Class. (or. Why is eval() messy?)

**URL:** <https://www.ruby-forum.com/t/dynamically-create-class-or-why-is-eval-messy/146423>\
**Category:** Ruby\
**Created:** [August 20, 2008, 10:31pm UTC](https://www.ruby-forum.com/t/dynamically-create-class-or-why-is-eval-messy/146423 "2008-08-20T22:31:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![lynchnco](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/c77e96/32.png) [@lynchnco](https://www.ruby-forum.com/u/lynchnco)\
**Post date:** [August 20, 2008, 10:31pm UTC](https://www.ruby-forum.com/t/dynamically-create-class-or-why-is-eval-messy/146423/1 "2008-08-20T22:31:47Z")

</div>

Hi,  
I’m trying to create a utility method that will automatically create a  
class for me, given a classname. But I can’t find a way around having to  
use eval().

This is what I’m doing right now:

def createClass(className)  
eval(\<\<-EOS)  
#{className} = Class.new do  
#bla bla bla  
end  
EOS  
end

but I really don’t like eval() and would like to avoid it, if at all  
possible.

Is there a reason, that Ruby doesn’t support something like this: Maybe  
because it’s inconsistent with something, or because it’s really hard?

className = “MyClass”  
methodName = “myMethod”

class \*className  
def \*methodName  
puts “yay!”  
end  
end

Also, I find eval() code really messy. Though I’m not sure why. I think  
I don’t like it, because my editor (IntelliJ) doesn’t do syntax  
highlighting for strings. Do you guys know of any editors that will  
syntax highlight a eval() string for you?

---

<div class="post-metadata">

**Author:** ![lynchnco](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/c77e96/32.png) [@lynchnco](https://www.ruby-forum.com/u/lynchnco)\
**Post date:** [August 20, 2008, 10:44pm UTC](https://www.ruby-forum.com/t/dynamically-create-class-or-why-is-eval-messy/146423/2 "2008-08-20T22:44:35Z")

</div>

On Wednesday 20 August 2008, Patrick Li wrote:

> ```
> #bla bla bla
> end
> 
> ```
> 
> EOS  
> end
> 
> but I really don’t like eval() and would like to avoid it, if at all  
> possible.

You’re almost there. This works

def create\_class name, mod = Object  
cls = Class.new do  
…  
end  
mod.constant\_set name, cls  
end

This allows to put the created class inside any module/class you like.  
If you  
don’t need it, simply remove it from the argument list and use Object in  
its  
place inside the method.

I hope this helps

Stefano

---

<div class="post-metadata">

**Author:** ![lynchnco](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/c77e96/32.png) [@lynchnco](https://www.ruby-forum.com/u/lynchnco)\
**Post date:** [August 20, 2008, 10:47pm UTC](https://www.ruby-forum.com/t/dynamically-create-class-or-why-is-eval-messy/146423/3 "2008-08-20T22:47:39Z")

</div>

Ah =), that’s quite lovely. Thank you.  
Until you suggested that, I was almost contemplating switching to Lisp  
or something.
