[Ruby]:将Class实例成员值传递给另一个Class函数

时间:2009-11-03 18:33:17

标签: ruby

我正在编写一个程序来读取文件并在其中搜索文本。我已经写了第一步。在下面给出的代码中,您可以看到符号** - **。这是我要传递Class [CurrentFile]的成员变量值。

还请建议我在此代码中可以做些哪些改进。

class CurrentFile
    attr_accessor :currentFileName, :currentFileContent
  end

class OpenFile < CurrentFile
    def OpenFileToRead()  #Open file as read-only.
      thisFile = File.open(** ----- **, 'r')
      counter = 1

        begin
          file = File.new(thisFile, "r")
          while (line = file.gets)
            puts "#{counter}: #{line}"
            counter = counter + 1
          end
          file.close
        rescue => err
          puts "Exception: #{err}"
          err
        end #End of Begin block
    end #End of OpenFileToRead
  end #End of Class: OpenFile

fileToRead = CurrentFile.new #Create instance of CurrentFile Class
fileToRead.currentFileName = "C:\WorkSpace\SearchText\abc.php" #Set file name to read
myFile = OpenFile.new #Create instance of OpenFile Class

2 个答案:

答案 0 :(得分:2)

您不需要两个课程。

由于OpenFile继承了CurrentFile,因此OpenFile中有 currentFileName currentFileContent 属性。这意味着您可以在currentFileName中使用File.open

fileToRead = OpenFile.new #Create instance of CurrentFile Class
fileToRead.currentFileName = "C:\WorkSpace\SearchText\abc.php" #Set file name to read
fileToRead.OpenFileToRead

或者如果你想要两个类而不是将currentFile实例作为参数传递给OpenFile而不是继承:

class OpenFile
    def initialize(file)
      @file = file
    end

    def OpenFileToRead()  #Open file as read-only.
      thisFile = File.open(@file.currentFileName, 'r')
      counter = 1

        begin
          file = File.new(thisFile, "r")
          while (line = file.gets)
            puts "#{counter}: #{line}"
            counter = counter + 1
          end
          file.close
        rescue => err
          puts "Exception: #{err}"
          err
        end
    end
  end

fileToRead = CurrentFile.new #Create instance of CurrentFile Class
fileToRead.currentFileName = "C:\WorkSpace\SearchText\abc.php" #Set file name to read
myFile = OpenFile.new(fileToRead) #Create instance of OpenFile Class
myFile.OpenFileToRead

答案 1 :(得分:0)

如果您尝试访问该实例的currentFileName属性,我想您只想写currentFileName