define_class and get_class

M

Mushtaq Ahmed

Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:

name = "A"
define_class(name) do
def say_hi
p "hi"
end
 
R

Robert Klemme

Mushtaq said:
Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:

name = "A"
define_class(name) do
def say_hi
p "hi"
end
.
.
end
get_class(name).new.say_hi


I would like the above syntax better than the current way of doing it.

name = "A"
eval "class #{name}; end"
klass = Object.const_get(name)
klass.class_eval do
def say_hi
p "hi"
end
.
.
end
klass.new.say_hi

-Mushtaq

cl = Class.new do
def say_hi() puts "hi!" end
end
hi!
=> nil=> "A"

Does that help?

Kind regards

robert
 
P

Paul Brannan

name = "A"
eval "class #{name}; end"
klass = Object.const_get(name)
klass.class_eval do
def say_hi
p "hi"
end
.
.
end
klass.new.say_hi

This is unnecessary.

A = Class.new
A.class_eval do
def say_hi
p "hi"
end
end

And as of 1.8, we can now also write:

A = Class.new do
def say_hi
p "hi"
end
end

Paul
 
D

daz

Mushtaq said:
Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:

name = "A"
define_class(name) do
def say_hi
p "hi"
end
.
.
end
get_class(name).new.say_hi


I would like the above syntax better than the current way of doing it.



module Kernel
def define_class(name, &blk)
klass = self.class.const_set(name, Class.new(&blk))
end

def get_class(name)
self.class.const_get(name)
end
end



name = 'D'

klass = define_class(name) do
def say_hi
p "hi #{self.class.name}"
end
end

get_class(name).new.say_hi #-> "hi D"


daz
 
R

Robert Klemme

Mushtaq said:
Not the same thing. I want to decide the class name at runtime. It
could be A, B, C or whatever.

cl = Class.new do
def foo() "bar" end
end

Object.const_set("AnyName", cl)
....

robert
 

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

No members online now.

Forum statistics

Threads
474,181
Messages
2,570,970
Members
47,537
Latest member
BellCorone

Latest Threads

Top