Classify a Ruby string
Classify a Ruby string
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
Answer by mway for Classify a Ruby string
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.
Answer by Mladen Jablanovi for Classify a Ruby string
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 #=> # Object.const_set class_name, klass #=> Module::MyClass MyClass.new.foo #=> "foo"
Answer by fifigyuri for Classify a Ruby string
For Classifying strings you can use active_support:
require 'active_support/core_ext/string' puts "hello_world" #=> "HelloWorld"
Answer by Cosmin Atanasiu for Classify a Ruby string
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 ?
Answer by Thomas07vt for Classify a Ruby string
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"
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment