Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically invoke or call a class in Rails?

Assuming I can construct a string that matches an existing class, how do I invoke it?

For example, I have several classes:

  • MyClass1
  • MyClass2
  • MyClass3

And I want to dynamically invoke each of them by constructing a string that matches their names. If they all had the method "methods", how do I do something like this?:

(1..3).each do |n|
  ("MyClass"+n).methods
end
like image 395
comb Avatar asked Jul 15 '12 07:07

comb


1 Answers

constantize fits the bill. You can read more about it here. In your case it would be something like:

(1..3).each do |n|
  "MyClass#{n}".constantize.methods
end
like image 121
zsquare Avatar answered Sep 23 '22 22:09

zsquare