2016-09-20 48 views
2

我有一個存儲類的名稱的變量裏面我的課讓Rails的識別字符串

my_class = "Homework" 

這個類有一定的屬性,我想訪問

Homework.find_by 

我怎樣才能讓紅寶石看到這個字符串作爲一個對象?

例如

my_class.find_by 

回答

3

您可以使用classifyconstantize

my_class.classify.constantize.find_by # something 

classify

Create a class name from a plural table name like Rails does for table names to models. Note that this returns a string and not a Class (To convert to an actual class follow classify with constantize).

constantize

Tries to find a constant with the name specified in the argument string.

'Module'.constantize  # => Module 
'Test::Unit'.constantize # => Test::Unit 

如果你確定你的輸入,你只需要constantize

my_class.constantize.find_by # something 
+0

'2.3.1:015 >'模塊'.constantize NoMethodError:未定義方法'constantize'爲「Module」:String' – Bula

+2

您需要導軌控制檯,而不是irb。 –