Ruby:未定义的方法*为nil nilclass

时间:2013-05-30 06:08:24

标签: ruby undefined

我在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>'

1 个答案:

答案 0 :(得分:7)

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

这就是为什么你的一个变量是nil并且典型异常NoMethodError: undefined method ... for nil:NilClass正在提升的原因。