Skizit
Skizit

Reputation: 44862

Question about inheritance in Ruby

I've been attempting to teach myself Ruby over the past while and I've been trying to get something like the following to work but I'm getting the following error...

file.rb:44:infunc': undefined local variable or method number' #<classname:0xb75d7840 @array=[]> (NameError)

The code that's giving me this error is...

 class A
     def func
          file = File.new("file", "r") 
      file.each_line {|line| @numbers << line.chomp.to_i}
          @number = @array[0]
     end
 end

 class B < A
     def func
       super number
       puts number
     end
 end

Could someone please tell me what I'm doing wrong?

edit// Just a clarification that I want number in class B to inherit the value of @number in class A.

Upvotes: 0

Views: 126

Answers (3)

Antal Spector-Zabusky
Antal Spector-Zabusky

Reputation: 36622

Your problem is that while you use the instance variable @number, calling super number (which isn't what you want, as this calls the superclass version of whatever method you're in, passing number as an argument) and puts number look up the method number. If you really do want to just look up the instance variable, you just need @number; if you want to define such a method, put one of the following lines in your class:

class A
  attr_accessor :number # Define reader (number) and writer (number=)
  attr_reader   :number # Define only a reader
  attr_writer   :number # Define only a writer; won't be useful here
  # ...
end

And as Ed Swangren said, you ought to clean up A: initialize variables in initialize, make sure you define everything before using it, etc.

Edit 1: Corrected the description of the behavior of super.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124790

You forgot the '@' symbol to reference the instance level variable.

It is a really bad design anyway. What if there are no lines in 'file'? @numbers is never initialized. You also wipe out @number completely on the next line with a variable (@array) that has never been defined. Stop trying to fit everything in as few lines as possible and properly initialize your variables.

EDIT: Also, as Chuck noticed, you are passing an argument to a method that takes no arguments.

Upvotes: 4

Chuck
Chuck

Reputation: 237110

Just like it's telling you, you're calling super and puts with an the argument number — but this number (whatever it's supposed to be) hasn't been defined anywhere. Define number to be something meaningful and the code will almost work. Almost.

The other mistake, which you'll discover after you've fixed that one, is that you're calling super number, which calls A's func method with this mysterious number object as the argument — but A#func doesn't take any arguments.

Upvotes: 4

Related Questions