问题
I have a program that create classes which looks like:
MyClass = Class.new do
def initialize; end
# ...
end
But I would like to name dynamically MyClass, from a string. And because it's for the name of a class, I would like to classify that string, for instance (thanks Rails methods):
"hello_world".classify # => "HelloWorld"
I don't know if in pure Ruby there is a method for that.
Thank you
回答1:
Not sure if your question is only about constructing a camelcased string, or also about assigning a newly created class to it. Because, for the latter, you should use Module::const_set
method:
class_name = 'MyClass'
#=> "MyClass"
klass = Class.new do
def foo
"foo"
end
end
#=> #<Class:0xa093a68>
Object.const_set class_name, klass
#=> Module::MyClass
MyClass.new.foo
#=> "foo"
回答2:
No, there isn't. Here's the String reference page.
You could do so like this:
"hello_world".split('_').collect!{ |w| w.capitalize }.join
You could easily implement this by reclassing the String class.
However, if you're using Rails for whatever reason, classify
is added for convenience, along with the underscore
method. I believe it's still used in Rails 3.
回答3:
If you wanted just to access the class from a string name, and not define it from a string, you can also use this:
MyClass = Class.new do
def test; end
# ...
end
"MyClass".constantize.test # => what you wanted ?
回答4:
This is much later, but I am going through this process and expanding on mway's answer I am using this:
class String
def classify
self.split('/').collect do |c|
c.split('_').collect(&:capitalize).join
end.join('::')
end
end
This will allow you to add namespaces to strings. So:
"api/post_comments".classify
=> "Api::PostComments"
来源:https://stackoverflow.com/questions/4072159/classify-a-ruby-string