5

I'd like to build a function "create" that gives me the following capabilities :

zoo=[]
zoo << create(:dog,4)
zoo[0].class #Dog class
myDog=zoo[0].new("foobar") #instance of Dog
myDog.legs #4 legs because my dog is a Dog
zoo[0].class.legs #4
zoo[0].class.superclass #Animal
zoo[0].class.superclass.legs #whatever, but they have legs

"create(:dog,4)" produces a new class Dog that inherits Animal etc

Can you help about this apparently simple metaprogramming question ?

1 Answer 1

5
class Animal
   def self.legs=(legs)
     @legs = legs
   end

   def self.legs
     @legs
   end

   def legs
     self.class.legs
   end
end

def create(sym, legs)
  klass = Object.const_set(sym.to_s.capitalize, Class.new(Animal))
  klass.legs = legs
  klass
end

kdog   = create(:dog, 4)
kalien = create(:alien, 3)

dog   = kdog.new
alien = kalien.new

puts kdog
puts kdog.class
puts kdog.superclass
puts kdog.legs

puts dog.class
puts dog.legs

puts "------"

puts kalien
puts kalien.class
puts kalien.superclass
puts kalien.legs

puts alien.class
puts alien.legs

Output:

Dog
Class
Animal
4
Dog
4
------
Alien
Class
Animal
3
Alien
3
Sign up to request clarification or add additional context in comments.

1 Comment

perfect ! I was stucked at Class.new. I was not aware of Class.new(Animal). Terrible !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.