Method_missing 而不是 运行 应该的时候

Method_missing not running when it should

我的程序中有一个团队 class,我正在尝试使用 method_missing 但是当方法不存在时,它不是 运行 函数,而是给我一个错误:"undefined method `hawks' for Team:Class (NoMethodError)"

我的代码如下:

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

您的代码有很多问题。让我们一一道来。

根据文档,

method_missing(*args) private Invoked by Ruby when obj is sent a message it cannot handle.

这里的message指的是method。在 ruby 中,每当您在对象上调用方法时,您实际上是在 sendmessage 传递给 object

为了更好地理解这一点,请在 irb shell 中尝试此操作。

1+2
=> 3
1.send(:+,2)
=> 3

这里1和2是Fixnumclass的对象。您可以使用 1.class 确认这一点。好的,回到你的问题。因此,应该在实例上调用 method_missing 方法。

team = Team.new
team.hawks

如果你尝试上面的代码,你会得到一个错误 'fetch': key not found: :roster (KeyError)

您可以通过将 default value 作为第二个参数传递给 fetch 方法来解决这个问题。将您的 initialize 方法替换为

def initialize(stats = {})
  @cust_roster = stats.fetch(:roster, [])
  @cust_total_per = stats.fetch(:per, 0)
  @cust_name = stats.fetch(:name, "anon")
  @cust_best_player = stats.fetch(:best, "anon")
  @@teams << self

结束

如果您执行该脚本,您会得到一个 stack level too deep (SystemStackError),因为此行中有一个小错字。

str = methID.id2name

在方法定义中,您收到一个名为 methId 的参数,但在内部您试图调用 methID。用

修复它
str = methId.id2name

如果您执行脚本,您将再次收到一条错误消息 undefined method uppercase for "hawks":String (NoMethodError)

这是因为字符串上没有 uppercase 方法。您应该改为使用 upcase 方法。

Team.new(roster:[], per: 0, name: str.upcase, best: 0)

你应该可以开始了。

有关更多信息,请参阅 http://apidock.com/ruby/BasicObject/method_missing

希望对您有所帮助!

class Team
  attr_accessor :cust_roster, :cust_total_per, :cust_name, :cust_best_player
  @@teams = []
  def initialize(stats = {roster: [], per: 0, name: "", best: 0}) # I added the default values here. 
    @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(name, *args)
    self.cust_name = name.to_s.upcase
  end

  class << self
    def all_teams
      @@teams
    end
  end

end

team_hawks = Team.new #=> create an instance of Team class, I renamed the object to avoid confusions. 
team_hawks.hawks      #=> called method_missing which assigned the cust_name variable to "HAWKS"

team_hawks.cust_name  #=> HAWKS, so cust_name is assigned to be hawks. This is to check if the assignment worked. 

希望这就是您要找的。