简体   繁体   English

Ruby:nil nilclass的未定义方法*

[英]Ruby: undefined method * for nil nilclass

I got the undefined method * for this code running in irb. 对于在irb中运行的此代码,我有未定义的方法*。 I'm using ruby 2.0.0p195 (2013-05-14) [i386-mingw32] on Windows 7 x32. 我在Windows 7 x32上使用ruby 2.0.0p195(2013-05-14)[i386-mingw32]。 It does two simple classes for geometrical shapes. 它为几何形状做了两个简单的类。

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

These are the commands with irb. 这些是带有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>'

You misspelled the method initialize and you wrote initalize . 您拼写了initialize方法,并写了initalize

That's why one of your variables is nil and the tipical exception NoMethodError: undefined method ... for nil:NilClass is raising. 这就是为什么您的变量之一为nil并且出现NoMethodError: undefined method ... for nil:NilClass异常NoMethodError: undefined method ... for nil:NilClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM