我在我的程序中有一个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 –