Consider I have a variable class_name. class_name can hold string values like blog, comment etc. based on the value inside class_name I need to create respective object.
If class_name is blog, I need to create a blog object. How can I achieve this without using a switch?
You'd use the camelize and constantize methods thusly:
klass = class_name.camelize.constantize
thing = klass.new
If you started with 'blog' in class_name, your klass would end up as Blog. If your string is actually 'Blog', then:
klass = class_name.constantize
thing = klass.new
Both camelize and constantize are Rails-specific but I see the "ruby-on-rails" tag so we're in Rails-land.
You can use Kernel.const_get but case is important.
a = 'Blog'
b = Kernel.const_get(a).new
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With