comb
comb

Reputation: 185

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:

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

Upvotes: 12

Views: 7668

Answers (2)

saihgala
saihgala

Reputation: 5774

you can also do -

(1..3).each {|n| eval "MyClass#{n}.methods"}

Upvotes: -3

zsquare
zsquare

Reputation: 10146

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

Upvotes: 20

Related Questions