ruby - 类初始化时出现 NoMethodError Ruby

标签 ruby class rspec nomethoderror

我正在通过在线类(class)进行“类(class)简介”练习。目标是创建一个用两个数字初始化的 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)>'

最佳答案

只需添加这一行

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 错误

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

关于ruby - 类初始化时出现 NoMethodError Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26162375/

相关文章:

ruby-on-rails - Rails 源代码 : initialize hash in a weird way?

c++ - 使用类而不是结构和构造函数问题

ruby-on-rails - 如何在 Rspec 中 stub 载波?

ruby - 任务依赖性是否总是以特定顺序与 rake 一起运行?

ruby - 这个 Ruby 使用 Class.new 来创建类,

c# - 抽象方法中的可选参数?是否可以?

Java Objects类和方法程序麻烦

ruby-on-rails - 使用 Capybara 和 Rspec 测试 Carrierwave 文件上传到 s3

ruby - 给定参数的 rspec 模拟返回

arrays - 将 Ruby 数组字符串转换为整数数组