0

TDD:

describe RPNCalculator do

  attr_accessor :calculator

  before do
    @calculator = RPNCalculator.new
  end

it "adds two numbers" do
  calculator.push(2)
  calculator.push(3)
  calculator.plus
  calculator.value.should == 5
end
end

我的代码:

class RPNCalculator
attr_accessor :calculator

def initialize()
  @calculator = []
end

def RPNCalculator(x=0,y=0)
@calculator.push(x)
@calculator.push(y)
@calculator.map {|x,y| x + y }
end

错误:

RPNCalculator
adds two numbers (FAILED - 1)

失败:

1)RPNCalculator adds two numbers
Failure/Error: calculator.push(2)
NoMethodError:
undefined method `push' for #<RPNCalculator:0x000000021b85a8 @calculator=[]>
4

2 回答 2

1

问题出在您调用的测试中calculator.push(2)RPNCalculator您在没有名为 的方法的对象上调用它push。它是类中的实例变量@calculator,您将其实例化为Array具有该方法的 。

您的测试实际上应该是:

it "adds two numbers" do
  @calculator.RPNCalculator(2,3).value.should == 5
end

我应该指出,方法名称以大写字母开头被认为是错误的形式。

如果我可能如此大胆地猜测您的测试试图得到什么,那么您想将push数字输入您的数字RPNCalculator并继续推动数字并随意获得这些数字的总和。如果确实如此,您可能正在寻找这样的东西:

class RPNCalculator
attr_accessor :calculator

def initialize()
  @calculator = []
end

def push(*num)
  # Use is_a? in order to ensure anything added to
  # the Array can later be added together 
  @calculator.push(*num) if num.all? {|n| n.is_a? Numeric}
  # If you would like this to work with any class that can be added
  # then change 'n.is_a? Numeric' to 'n.respond_to? :+'
end

def plus
  @calculator.reduce(:+)
end

def value
  plus
end

这样做应该使您的原始测试无需更改即可工作。

使用示例:

calc = RPNCalculator.new
calc.push(3)
calc.push(2)
calc.plus #=> 5
calc.push(6)
calc.plus #=> 8   
calc.push(1,2,3,4)
calc.plus #=> 18

请注意,我在方法定义中使用了 splat 运算符(星号)。我建议对这个主题进行一些阅读。值得学习和喜爱。

于 2013-04-02T18:19:05.677 回答
0

试试这个:

class RPNCalculator
attr_accessor :calculator

def initialize()
  @calculator = []
end

def RPNCalculator(x=0,y=0)
  @calculator.push(x)
  @calculator.push(y)
  p @calculator.reduce(&:+)
end
end

cal = RPNCalculator.new
cal.RPNCalculator(10,20) #30
于 2013-04-02T18:14:21.357 回答