Search code examples
rubyclassinstancenomethoderror

Why does this class definition result in a NoMethodError?


I've looked for a solution to this, but the most relevant answers seem to prescribe using self., which I'm already doing; I'm unable to phrase my search in such a way that I can find what I'm doing wrong. I'm defining a class as below, but when I try to create an instance I get

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

I've tried defining valid_pegs? as an instance method instead, which I can get to work if I call it as such, but this is a problem for a course, and I'm expected to define it as a class method.

So why doesn't it work?

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

Solution

  • You are almost there!

    if !self.class.valid_pegs?(peg_arr)
    

    or

    if !Code.valid_pegs?(peg_arr)
    

    Defining a self.function-method(in this case, self.valid_pegs) is a "class level" or a singleton method.
    While the "self" used inside the class definition is just a reference to the object.