首页 > 解决方案 > Ruby:处理布尔值

问题描述

TDD

gem 'minitest', '~> 5.2'
require 'minitest/autorun'
require 'minitest/pride'
require_relative 'santa'

class SantaTest < Minitest::Test

 def test_santa_fits_down_the_chimney
  santa = Santa.new
  assert santa.fits?, "Santa fits down the chimney"
 end

 def test_if_santa_eats_too_many_cookies_he_does_not_fit_down_the_chimney

  santa = Santa.new
  santa.eats_cookies
  assert santa.fits?, "He still fits"

  santa.eats_cookies
  assert santa.fits?, "It's a bit of a sqeeze"

  santa.eats_cookies
  refute santa.fits?, "Good thing his suit is stretchy or that wouldn't 
  fit in that either"
 end
end

代码

class Santa
 attr_reader :eats_cookies

 def initialize
  @eats_cookies = eats_cookies
 end

 def fits?
  true unless @eats_cookies > 2
 else
  false
 end
end

关于我可以写什么以使测试通过最后一次测试的任何指示?我在组织 if/then、unless/else 语句以使测试通过时遇到问题。

我是在正确的轨道上还是我离得很远?感谢任何帮助

标签: ruby

解决方案


我在推断你想在这里做什么,但我想我会做这样的事情:

class Santa
  attr_accessor :cookies_eaten

  def initialize
    @cookies_eaten = 0
  end

  def eat_cookies
    self.cookies_eaten += 1
  end

  def fits?
    cookies_eaten <= 2
  end
end

推荐阅读