0

I got the undefined method * for this code running in irb. I'm using ruby 2.0.0p195 (2013-05-14) [i386-mingw32] on Windows 7 x32. 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(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
  • 1
    One of your variables is nil... So you can not multiply by nil. Commented May 30, 2013 at 6:11

1 Answer 1

7

You misspelled the method initialize and you wrote initalize.

That's why one of your variables is nil and the tipical exception NoMethodError: undefined method ... for nil:NilClass is raising.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.