metaprogramming - Ruby: Dynamically create new classes -
i'm trying dynamically create set of classes follows.
class foo attr_reader :description end ['alpha', 'beta', 'gamma'].each |i| klass = class.new(foo) |i| def initialize @description = end end object.const_set(i, klass) end
rather creating each class manually, e. g.:
class alpha < foo def initialize @description = 'alpha' end end
what right way such thing , how pass iterator nested block?
how pass iterator nested block?
by using nested block. def not block. def cuts off visibility of variables outside def. block on other hand can see variables outside block:
class foo attr_reader :description end ['alpha', 'beta', 'gamma'].each |class_name| klass = class.new(foo) define_method(:initialize) @description = class_name end end object.const_set(class_name, klass) end = alpha.new p a.description --output:-- "alpha"
you can want without having create nested block or class foo:
['alpha', 'beta', 'gamma'].each |class_name| klass = class.new() def initialize @description = self.class.name end attr_reader :description end object.const_set(class_name, klass) end --output:-- "alpha" "gamma"
Comments
Post a Comment