为什么这个类定义会导致NoMethodError?

问题描述 投票:0回答:1

我一直在寻找解决方案,但是最相关的答案似乎是使用self.来规定的,我已经在这样做了;我无法以这样一种方式来表达我的搜索字词,即可以发现自己在做错什么。我正在定义一个类,如下所示,但是当我尝试创建一个实例时,我得到

NoMethodError:
       undefined method `valid_pegs?' for #<Code:0x00007fffc58d1608>

我尝试将valid_pegs?定义为实例方法,如果这样调用它可以正常工作,但这在课程中是一个问题,我希望将其定义为类方法。

所以为什么不起作用?

class Code
  POSSIBLE_PEGS = {
    "R" => :red,
    "G" => :green,
    "B" => :blue,
    "Y" => :yellow
  }

  attr_reader :pegs

  def self.valid_pegs?(peg_arr)
    outcome = true
    peg_arr.each {|peg| outcome = false if !POSSIBLE_PEGS.include?(peg.upcase)}
    return outcome
  end

  def initialize(peg_arr)
    if !self.valid_pegs?(peg_arr)
      raise "Those are not all valid pegs"
    else
      @pegs = []
      peg_arr.each {|peg| @pegs << peg.upcase}
    end
  end

end
ruby class instance nomethoderror
1个回答
0
投票

您快到了!

if !self.class.valid_pegs?(peg_arr)
© www.soinside.com 2019 - 2024. All rights reserved.