NoMethodError Ruby on Class Initialize

时间:2014-10-02 13:54:02

标签: ruby class rspec nomethoderror

我正在做一个"课程简介"通过在线课程锻炼。目标是创建一个用两个数字初始化的类Calculator。然后可以对这些数字进行加,减,乘和除。我的代码似乎在本地环境中起作用:

class Calculator
  def initialize(x,y)
    @x, @y = x, y
  end
  def self.description
    "Performs basic mathematical operations"
  end
  def add
    @x + @y
  end
  def subtract
    @x - @y
  end
  def multiply
    @x * @y
  end
  def divide
    @x.to_f/@y.to_f
  end
end

但该网站有Rspec规格:

describe "Calculator" do
  describe "description" do
    it "returns a description string" do
      Calculator.description.should == "Performs basic mathematical operations"
    end
  end
  describe "instance methods" do
    before { @calc = Calculator.new(7, 2) }
    describe "initialize" do
      it "takes two numbers" do
        expect( @calc.x ).to eq(7)
        expect( @calc.y ).to eq(2)
      end
    end
    describe "add" do
      it "adds the two numbers" do
        expect( @calc.add ).to eq(9)
      end
    end
    describe "subtract" do
      it "subtracts the second from the first" do
        expect( @calc.subtract ).to eq(5)
      end
    end
    describe "multiply" do
      it "should return a standard number of axles for any car" do
        expect( @calc.multiply ).to eq(14)
      end
    end
    describe "divide" do
      it "divides the numbers, returning a 'Float' if appropriate" do
        expect( @calc.divide ).to eq(3.5)
      end
    end
  end
end

并且网站的规范会抛出NoMethodError:

NoMethodError
undefined method `x' for #<Calculator:0x007feb61460b00 @x=7, @y=2>
    exercise_spec.rb:14:in `block (4 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:3)

只需添加此行

即可
attr_reader :x, :y

以下是更正后的代码:

class Calculator
  attr_reader :x, :y

  def initialize(x,y)
    @x, @y = x, y
  end
  def self.description
    "Performs basic mathematical operations"
  end
  def add
    # once you defined reader method as above you can simple use x to get the
    # value of @x. Same is true for only y instead of @y.
    x + y 
  end
  def subtract
    x - y
  end
  def multiply
    x * y
  end
  def divide
    x.to_f/y.to_f
  end
end

查看以下规范代码: -

describe "initialize" do
      it "takes two numbers" do
        expect( @calc.x ).to eq(7)
        expect( @calc.y ).to eq(2)
      end
      #...

您正在呼叫@calc.x@calc.y。但是您没有将名为#x#y的任何方法定义为类Calculator中的实例方法。这就是为什么你得到NoMethod error的非常明确的例外。

当您编写attr_reader :x, :y时,它将在内部为您创建这些方法。阅读此answer以了解Ruby中的 reader writer 方法。