2015-05-17 3 views
-2
# As a user, you can initialize the guessing game with a number, which is 
the correct guess 
# so the initialize method takes in one parameter, and sets game_complete? 
to false 
# 
# As a user, I can guess the number, which will 
# return :too_high if its > answer 
# return :too_low if its < answer 
# return :correct if its = answer 
# correct changes the game_complete? to true 
# if a user guesses the incorrect number after guessing the correct number, 
it should 
# change the game_complete? to false 
# return :too_high or :too_low 
require_relative 'guess' 
describe GuessingGame do 
let(:game) { GuessingGame.new(50) } 
describe "#initialize" do 
it "expects a single parameter" do 
    expect(GuessingGame.instance_method(:initialize).arity).to eq 1 
    end 
end 
describe "#guess" do 
it "expects a single parameter" do 
    expect(GuessingGame.instance_method(:guess).arity).to eq 1 
end 

it "returns :too_low when the guess is lower than the answer" do 
    expect(game.guess(1)).to eq :too_low 
end 

it "returns :too_high when the guess is higher than the answer" do 
    expect(game.guess(100)).to eq :too_high 
end 

it "returns :correct when the guess matches answer" do 
    expect(game.guess(50)).to eq :correct 
end 

it "changes game_complete? when the correct guess is made" do 
    expect { 
    game.guess(50) 
    }.to change(game, :game_complete?).from(false).to(true) 
end 

it "doesn't change game_complete? when an incorrect guess is made" do 
    expect { 
    game.guess(10) 
    }.to_not change(game, :game_complete?).from(false) 
end 

it "returns :game_solved once you try to guess in a completed game" do 
    game.guess(50) 
    expect(game.guess(100)).to eq :game_solved 
    end 
end 

describe "#game_complete?" do 
it "returns false in a new game" do 
    expect(game.game_complete?).to eq false 
end 
    end 
end 

Теперь, когда я запускаю этот код, я получаю ошибку GuessingGame # угадывать возвращаюсь: game_solved раза вы пытаетесь угадать, в завершенной игрелогические методы в рубине на рельсах

это мой класс догадки

class GuessingGame 
    def initialize(num) 
     @num=num 
     def game_complete? 
      return false 
     end 
    end 
    def guess(num1) 
     if num1<@num 
      return :too_low 
     elsif num1>@num 
      return :too_high 
     else 
      def game_complete? 
       return true 
      end 
      return :correct 
     end 
end 

конец

Я пытался инициализировать переменную Ьоо с ложными и когда-то правильное предположение делается я сделал это верно, и если эта переменная правда я вернусь: game_completed но не работало для меня

+0

Это не инициализация переменных. Это определяющие методы. Абсолютно другой. Какой учебник/курс вы следуете? –

+0

Его не онлайн-курс. Это учебный курс для вузов –

+1

Если они вас учат, вы должны найти другой институт :) –

ответ

1

Похоже, что вы не инициализируете тему, если только нет кода, который вы не показываете. Вот версия, которая работает:

class GuessingGame 

    def initialize(num) 
    @num = num 
    end 

    def guess(num) 
    if num < @num 
     return :too_low 
    elsif num > @num 
     return :too_high 
    else 
     return :correct 
    end 
    end 

end 

require 'spec_helper' 
require 'foo' 

describe GuessingGame do 
    let(:foo) { GuessingGame.new(50) } 

    describe "when guess is too low" do 
    it "returns :too_low" do 
     expect(foo.guess(25)).to eq :too_low 
    end 
    end 

    describe "when guess is too high" do 
    it "returns :too_high" do 
     expect(foo.guess(75)).to eq :too_high 
    end 
    end 

    describe "when guess is correct" do 
    it "returns :correct" do 
     expect(foo.guess(50)).to eq :correct 
    end 
    end 

end 

Теперь некоторые рефакторинг. Обычно не рекомендуется возвращаться из середины метода. Ruby всегда возвращает значение последнего выражения, поэтому мы можем воспользоваться этим.

def guess(num) 
    case num <=> @num 
    when -1 
     :too_low 
    when 1 
     :too_high 
    else 
     :correct 
    end 
    end 

<=> Оператор сравнивает два значения и возвращает -1, 0 или 1. С небольшой изворотливостью мы можем дополнительно реорганизовать guess метод на одну строку с:

def guess(num) 
    [:correct, :too_high, :too_low][num <=> @num] 
    end 

EDIT

It похоже, вы также хотите определить другой метод, чтобы указать, завершена ли игра. Вот один из способов сделать это:

class GuessingGame 

    def initialize(num) 
    @num = num 
    end 

    def compare(num) 
    [:correct, :too_high, :too_low][num <=> @num] 
    end 

    def guess(num) 
    @comparison = compare(num) 
    end 

    def game_complete? 
    @comparison == :correct 
    end 

end 
+1

есть мой +1 для скрытности :) –

+0

добавлен полный код, теперь вы можете снова проверить –

0

Возможно, вы можете попробовать что-то вроде этого, вместо того, чтобы определять методы, просто превращайте их в переменную.

class GuessingGame 
    attr_reader :game_complete 
    def initialize(num) 
    @num=num 
    end 

    def guess(num1) 
    if num1<@num 
      return :too_low 
    elsif num1>@num 
     return :too_high 
    else 
     @game_complete = true 
    end 
    return :correct 
    end 
end 

Теперь, чтобы проверить, если игра будет сделано, вы можете использовать game.game_complete который будет возвращать nil, если это не полный (который оценивается как ложное), или, если это compelte он вернется true. Надеюсь, это вам поможет.

Смежные вопросы