开发者

[Ruby]: Passing a Class instance member value to another Class function

开发者 https://www.devze.com 2022-12-10 15:29 出处:网络
I am writing a program to read files and search text in it. I have written the first initial steps. In the below given code you can see a symbol ** -- **. This where I want to pass member variable val

I am writing a program to read files and search text in it. I have written the first initial steps. In the below given code you can see a symbol ** -- **. This where I want to pass member variable value of Class [CurrentFile].

Please also suggest what improvements I can do in this code.

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
   开发者_JAVA技巧     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


You don't need two classes.

Since OpenFile inherits CurrentFile then you have currentFileName and currentFileContent attributes in OpenFile. This means you can use currentFileName in File.open.

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

Or if you want two classes than pass a currentFile instance as a parameter to OpenFile and don't inherit:

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


I think you just want to write currentFileName if you're trying to access that instance's currentFileName attribute.

0

精彩评论

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

关注公众号