Использовать Модуль # const_set . Он автоматически включается в Object, поэтому вы можете делать такие вещи, как:
foo.rb
# Defining the class dynamically. Note that it doesn't currently have a name
klass = Class.new do
attr_accessor(:args)
def initialize(*args)
@stuff = args
end
end
# Getting the class name
class_name = ARGV[0].capitalize
# Assign it to a constant... dynamically. Ruby will give it a name here.
Object.const_set(class_name, klass)
# Create a new instance of it, print the class's name, and print the arguments passed to it. Note: we could just use klass.new, but this is more fun.
my_klass = const_get(class_name).new(ARGV[1..-1])
puts "Created new instance of `" << my_klass.class << "' with arguments: " << my_klass.args.join(", ")
Я еще не пробовал этот код, но он должен выдать что-то вроде:
$ ruby foo.rb RubyRules pancakes are better than waffles
Created new instance of `RubyRules' with arguments: pancakes, are, better, than, waffles
Кроме того, первый аргумент const_set
абсолютно должен начинаться с заглавной буквенно-цифровой буквы (как статическое определение констант), иначе Ruby выдаст ошибку, похожую на следующую:
NameError: wrong constant name rubyRules
--- INSERT STACKTRACE HERE ---