【问题标题】:Class and instance methods are both invoked by test, how could I "merge" them?类和实例方法都是通过测试调用的,我如何“合并”它们?
【发布时间】:2014-10-03 03:23:58
【问题描述】:

我坚持使用来自 exercism.io 的这个练习:

sum_of_multiples_test.rb 的一部分

...
  def test_sum_to_1000
    skip
    assert_equal 233168, SumOfMultiples.to(1000)
  end

  def test_configurable_7_13_17_to_20
    assert_equal 51, SumOfMultiples.new(7, 13, 17).to(20)
  end
...

sum.rb

class SumOfMultiples
  def initialize(*args)
    @args = args ||= [3,5]
  end

  def to(max)
    ary = []
    return 0 if max < 2
    @args.each do |m|
      for i in 0..max-1
        ary << i if i % m == 0
      end
    end
    ary.uniq!.inject(:+)
  end
end

如果我使用类方法self.to,它看不到我的实例变量@args,如果我使用 实例方法“def to”第一个测试不通过。有没有办法以某种方式“合并”两者?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    向你的类添加另一个方法:

    def self.to(max)
      new.to(max)
    end
    

    您现在可以调用其中的每一个,结果都是一样的:

    SumOfMultiples.to(1000)
    SumOfMultiples.new.to(1000)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多