dimanche 26 mars 2023

How can I make recursion works correctly in Ruby?

I'm trying to code a Mastermind game with Ruby. It's an exercise from https://www.theodinproject.com/lessons/ruby-mastermind.

I build a method #make-guess that loops 4 times taking input from the user and validating it i.e making sure that the input is included in #BALL array.

For that, I declared a condition if the input is included in the #BALL array, append it to an array #guess, and else, call the function again (recursion).

The problem is when an input is not included, the function #make-guess loops more than 4 times. Here is the code I'm working on:

class MasterMind
  BALLS = ['r', 'g', 'o', 'y', 'v', 'm']

  comp_selection = BALLS.sample(4)

  def make_guess
    guess = []
    until guess.length == 4
      puts "Guess the computer's combination from: 'r', 'g', 'o', 'y', 'v', 'm'"
      value = gets.chomp
      if BALLS.include?(value)
        guess.append(value)
      else
        puts 'Selection not in the combination, try again'
        make_guess
      end
    end
    guess
  end

end

master = MasterMind.new
puts master.make_guess

Aucun commentaire:

Enregistrer un commentaire