Ruby 语法错误,输入意外结束,需要关键字\u end(帮助我)!
得到了这个错误,但无法找出我需要结束的地方Ruby 语法错误,输入意外结束,需要关键字\u end(帮助我)!,ruby,Ruby,得到了这个错误,但无法找出我需要结束的地方 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" => :gr
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
test/test1:54:方法体中的类定义
test/test1:79:语法错误,输入意外结束,应为关键字\u end
类别代码
属性读取器:pegs
def初始化(pegs)
@@pegs_键={“R”=>:红色,“G”=>:绿色,“B”=>:蓝色,“Y”=>:黄色,
“O”=>:橙色,“P”=>:紫色}
@钉子
结束
类Make
所以
看起来像guess.color\u计数器。每个do
都没有终止;另外,if code\u counter[color]>计数?matches+=count:matches+=code\u counter[color]
可能不符合您的想法我在“matches-self.exact\u matches(guess)”之后添加了一个end,这消除了第一个错误,但是test/test1:79:语法错误,输入意外结束,期望关键字\u end仍然存在。对于if-else-one行,我希望取较小的值并将其添加到“matches”中
if code_counter[color] > count ? matches += count : matches += code_counter[color]
matches += (code_counter[color] > count ? count : code_counter[color])