我在我的程序中有一個Team類,我試圖使用method_missing ,但是當方法不存在時不運行該函數,它給了我一個錯誤:「undefined method`老鷹隊的球隊:類(NoMethodError)」Method_missing not running when it should
我的代碼如下:
class Team
attr_accessor :cust_roster, :cust_total_per, :cust_name, :cust_best_player
@@teams = []
def initialize(stats = {})
@cust_roster = stats.fetch(:roster) || []
@cust_total_per = stats.fetch(:per)
@cust_name = stats.fetch(:name)
@cust_best_player = stats.fetch(:best)
@@teams << self
end
def method_missing(methId)
str = methID.id2name
Team.new(roster:[], per: 0, name: str.uppercase, best: 0)
end
class <<self
def all_teams
@@teams
end
end
end
hawks = Team.hawks
你是不是指'hawks = Team.new.hawks'? 'Team.hawks'試圖調用不存在的類方法'hawks'。 –
或者'def self.method_missing'? – ScottJ
不行,因爲Team.new已經是一個函數,它不會運行method_missing –