I have a code that is not giving the desired return. Below is the code
class Turn
def initialize(passcode:)
@passcode = passcode
end
def guess(colors)
result = []
passcode.each_with_index do |passcode_color, idx|
if colors[idx] == passcode_color
result << :exact
elsif colors.include?(passcode_color)
result << :partial
end
end
result
end
private
attr_reader :passcode
end
passcode = ["RED", "GREEN", "BLUE", "YELLOW"]
player = Turn.new(passcode: passcode)
player.guess(["RED", "GREEN", "BLUE", "GREEN"]
The above method call gave this output => [:exact,:exact, :exact].
Meanwhile this is my desired output => [:exact,:exact, :exact, :partial].
I think the last color (GREEN) in the colors array is included in the passcode but not at the exact position, hence expecting partial.
Please, how can I modify the code to get this output => [:exact,:exact, :exact, :partial].
CodePudding user response:
Well, "YELLOW"
isn't in colors
so nothing is added to your result
for that eventuality.
You may instead wish to use #map
. Using the following, in the "YELLOW"
case, nil
will be added the resulting array.
class Turn
def initialize(passcode:)
@passcode = passcode
end
def guess(colors)
@passcode.each_with_index.map do |passcode_color, idx|
if colors[idx] == passcode_color
:exact
elsif colors.include? passcode_color
:partial
end
end
end
end
If you want to include something like :notfound
for that scenario, you could add an else
.
class Turn
def initialize(passcode:)
@passcode = passcode
end
def guess(colors)
@passcode.each_with_index.map do |passcode_color, idx|
if colors[idx] == passcode_color
:exact
elsif colors.include? passcode_color
:partial
else
:notfound
end
end
end
end