leap.rb找不到模块错误

时间:2014-03-30 22:42:06

标签: ruby

想知道是否有人能看出为什么我不能打电话.modulo。我觉得我必须在课堂上调用Math,但我不确定是不是这样。

git:https://github.com/jbasalone/ja/tree/master/ruby/exercism.io/leap

错误:

test_leap_year(YearTest):
    NoMethodError: undefined method `modulo' for nil:NilClass
    /Users/jennyb/ja/ja/ruby/exercism.io/leap/year.rb:26:in `divbyfour?'
    /Users/jennyb/ja/ja/ruby/exercism.io/leap/year.rb:17:in `leap?'
    leap_test.rb:6:in `test_leap_year'

这是我的代码:

class Year

    def initialize(theyear)
        @theyear = theyear
    end
class << self

    attr_reader :theyear

    def initialize(theyear)
        @theyear = theyear
    end

    def leap?(theyear)
        divbyfour? && !acentury? || bcentury?
    end
    #private

    def acentury?
        theyear.modulo 100 == 0
    end

    def divbyfour?
        theyear.modulo 4 == 0
    end

    def bcentury?
        theyear.modulo 400 == 0 
    end
    end
    end

这是我对它进行的测试:

require 'minitest/autorun'
require_relative 'year'

class YearTest < MiniTest::Unit::TestCase
   def test_leap_year
     assert Year.leap?(1996)
   end

  def test_non_leap_year
    skip
    refute Year.leap?(1997)
  end

  def test_non_leap_even_year
    skip
    refute Year.leap?(1998)
  end

  def test_century
    skip
    refute Year.leap?(1900)
  end

  def test_fourth_century
    skip
    assert Year.leap?(2400)
  end
end

2 个答案:

答案 0 :(得分:0)

divbyfour方法中,您在modulo变量上调用了theyear,但该变量并不存在。

这是修复问题的代码。

class Year
  attr_reader :theyear

  def initialize(theyear)
    @theyear = theyear
  end

  def leap?
    divbyfour? && !acentury? || bcentury?
  end

  def acentury?
    theyear.modulo(100) == 0
  end

  def divbyfour?
    theyear.modulo(4) == 0
  end

  def bcentury?
    theyear.modulo(400) == 0
  end
end

示例:

>> year = Year.new 2014
=> #<Year:0xb8eb15b4 @theyear=2014>
>> year.leap?
=> false

我做了什么:

如果你有时间,请查看Ruby Koans - 这是学习Ruby及其习语的好方法。

答案 1 :(得分:0)

这对我有用:

class Year

    attr_accessor :theyear

    def initialize(theyear)
        @theyear = theyear
    end

    def leap?
        divbyfour? && !acentury? || bcentury?
    end
    #private

    def acentury?
        theyear.modulo(100) == 0
    end

    def divbyfour?
        theyear.modulo(4) == 0
    end

    def bcentury?
        theyear.modulo(400) == 0 
    end
end

然后你用:

来称呼它
y = Year.new(1995)
y.leap?

或者您可以像这样使用它:

class Year

    def self.leap?(year)
        @theyear = year
        divbyfour? && !acentury? || bcentury?
    end

    def self.theyear
      @theyear
    end
    #private

    def self.acentury?
        theyear.modulo(100) == 0
    end

    def self.divbyfour?
        theyear.modulo(4) == 0
    end

    def self.bcentury?
        theyear.modulo(400) == 0 
    end
end

然后你不需要初始化Year类。

Year.leap?(1995)
=> false