开发者

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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜