Phi Truong Phi Truong - 3 months ago 16
Ruby Question

syntax error, unexpected end-of-input, expecting keyword_end ( help me )!

got this error but cant figure out where i need to put an end.

test/test1:54: class definition in method body
test/test1:79: syntax error, unexpected end-of-input, expecting keyword_end



class Code
attr_reader :pegs

def initialize(pegs)
@@pegs_key = { "R" => :red,"G" => :green,"B" => :blue,"Y" => :yellow,
"O" => :orange,"P" => :purple }
@pegs = pegs
end

class << self
def random
rand_pegs_set = []
4.times { rand_pegs_set << @@pegs_Key.values.sample }
Code.new(rand_pegs_set)
end

def parse(str)
str = string.split("")
pegs_set = []
str.each do |letter|
if @@pegs_key.has_key?(letter.upcase)
pegs_set << @@pegs_key[letter.upcase]
else
raise "Incorrect colors"
end
end
Code.new(pegs_set)
end
end

def exact_matches(guess)
matches = 0
pegs_set.each_with_index { |color,i| matches += 1 if self[i] == color }
matches
end

def color_counter
counter = Hash.new(0)
@pegs.each { |color| counter[color] += 1 }
counter
end

def near_matches(guess)
matches = 0
code_counter = self.color_counter
guess.color_counter.each do |color,count|
if code_counter.has_key?(color)
if code_counter[color] > count ? matches += count : matches += code_counter[color]
end
matches - self.exact_matches(guess)
end
end

class Game
attr_reader :secret_code

def initialize(secret_code = Code.random)
@secret_code = secret_code
end

def play
10.times do
puts "Enter your guess"
guess = Code.parse(gets.chomp)
if guess == @secret_code
puts "Great Job! you got it"
break
end
show_matches(guess)
end
end

def show_matches(guess)
exact_matches = @secret_code.exact_matches(guess)
near_matches = @secret_code.near_matches(guess)
puts "#{exact_matches} were exactly right"
puts "#{near_matches} were nearly a match"
end
end

Answer

Make

if code_counter[color] > count ? matches += count : matches += code_counter[color]

so

matches += (code_counter[color] > count ?  count : code_counter[color])
Comments