amrnt
amrnt

Reputation: 1331

Is there any hack to override a class name with custom one?

Let's say I have a class Set I want something like this for example

class Set
  def initialize(new_name)
    self.class = new_name
  end
end

If you do something like that x = Set.new("Dog"), x.class will return Dog instead of Set. The class above is not working as well!

Upvotes: 1

Views: 1552

Answers (1)

amrnt
amrnt

Reputation: 1331

I figured it out! this should work ;)

class Obj
  def initialize(name)
    @klass = Object.const_set(name.capitalize, Class.new()).new()
  end
end

Give it a try:

dog = Obj.new("dog")
dog.class #=> Dog
dog.class.name #=> "Dog"

Upvotes: 3

Related Questions