0
我有以下方法:訪問模型的方法,而無需創建一個對象
class Store < ActiveRecord::Base
def my_func(str)
puts str
end
end
我似乎無法從類的外部調用它是這樣的:
Store::my_func("hi")
知道爲什麼?
我有以下方法:訪問模型的方法,而無需創建一個對象
class Store < ActiveRecord::Base
def my_func(str)
puts str
end
end
我似乎無法從類的外部調用它是這樣的:
Store::my_func("hi")
知道爲什麼?
你定義的是一個實例方法。基本上這意味着您只能在該類的實例上調用它。
store = Store.new
store.my_func("hi")
如果你想有一個類方法,你需要以不同的定義它一點點。或者:
class Store < ActiveRecord::Base
def self.my_func(str)
puts str
end
end
或(更多有用的,如果你定義了很多類方法):
class Store < ActiveRecord::Base
class << self
def my_func(str)
puts str
end
end
end
上述兩項工作,因爲類也類Class
的情況下,這樣的隱性接收機上面兩個例子中的self
就是那個實例(類本身)。
你調用一個類的方法是這樣的:
Store.my_func("hi")
感謝真棒解釋! – Hopstream
這僅適用於實例:'Store.new.my_func( 「HI」)' – mliebelt