Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an object using the content inside a variable in Ruby?

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?

like image 305
Rahul Avatar asked Sep 16 '26 16:09

Rahul


2 Answers

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.

like image 200
mu is too short Avatar answered Sep 18 '26 05:09

mu is too short


You can use Kernel.const_get but case is important.

a = 'Blog'
b = Kernel.const_get(a).new
like image 39
Gazler Avatar answered Sep 18 '26 06:09

Gazler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!