Mastermind Spec Demands Infinite Loop?

Why in the world would the specs require that parse and random within the code class return a new instance of the same class? it seems to not make any sense whatsoever. Every time initialize is called, parse is called and creates a new code, which in turn causes parse to be called again, and so the cycle repeats into infinity.

Wouldn’t it make more sense to return an array?
I wrote a functional Mastermind game using no classes at all, just element and position checks.

Agreed. Pretty confusing.

I used…

::parse to create an instance with a given code
::random to create an instance with a random code

Both create a new Code object by calling #new (#initialize). I think they want us to solidify using factory methods, creating/comparing objects, etc… I don’t know if this helps or does anything for you but I do understand what you mean.

PEGS = { red: "R", green: "G", blue: "B",
       yellow: "Y", orange: "O", purple: "P" }

def initialize(code)
  @pegs = code
end

def self.parse(code)
  peg_codes = PEGS.values
  code.each_char do |ch|
    unless peg_codes.include?(ch.upcase)
      raise "Invalid code!"
    end
  end

  new(code.upcase.chars)
end

def self.random
  new( (0..3).map { PEGS.values.sample } )
end

I certainly would have phrased it a lot differently but then again I’ve got some experience as a writer

Hey Aaron,

Technically you can create Mastermind or any program without using classes or object-oriented programming. Although this is very possible, this isn’t good in practice. Once a program becomes more complex, it becomes harder to track what is going on. Object-oriented programming allows a developer to abstract ideas and reuse code. Eventually, you’ll learn the importance of DRY (Don’t Repeat Yourself) and SRP (Single Responsibility Principle). The purpose of the mastermind exercise is to help you get more familiar with Object Oriented Programming, class interactions, and factory methods.

I hope this helps.

Sally