0

我得到了在 irb 中运行的这段代码的未定义方法 *。我在 Windows 7 x32 上使用 ruby​​ 2.0.0p195 (2013-05-14) [i386-mingw32]。它为几何形状做了两个简单的类。

class Shape
  ERR = 'Error: area or perimeter method missing.'
  PI  = 3.14159265358
  attr_accessor :id

  def initalize(id = 'shape')
    @id = id
  end

  def get_area
    raise ERR
  end

  def get_perimeter
    raise ERR
  end

  def to_s
    "id: #{@id}, area: #{get_area}, perimeter: #{get_perimeter}"
  end
end

class Triangle < Shape
  attr_accessor :a, :b, :c, :h

  def initalize(id = 'triangle', a = 1, b = 2, c = 3, h = 4)
    @id = id
    @a, @b, @c, @h = a, b, c, h
  end

  def get_area
    @b * @h * 0.5
  end

  def get_perimeter
    @a + @b + @c
  end
end

这些是带有 irb 的命令。

irb(main):001:0> load 'shapes.rb'
=> true
irb(main):002:0> tri = Triangle.new
=> #<Triangle:0x22d17c8>
irb(main):003:0> puts tri
NoMethodError: undefined method `*' for nil:NilClass
        from shapes.rb:41:in `get_area'
        from shapes.rb:28:in `to_s'
        from (irb):3:in `puts'
        from (irb):3:in `puts'
        from (irb):3
        from D:/Ruby/bin/irb:12:in `<main>'
4

1 回答 1

7

你拼错了方法initialize,你写了initalize

这就是为什么您的变量之一是nil并且典型的例外NoMethodError: undefined method ... for nil:NilClass正在引发。

于 2013-05-30T06:12:30.433 回答