LoginSignup
6
6

More than 5 years have passed since last update.

rubyでファイルのマージ

Posted at

久しぶりにrubyを勉強しました。ファイルに新しい行を挿入してそれ以降の行を下にずらすような処理です。

sample.rb
#!/usr/bin/ruby

class ConfigfileMerge
    attr_reader :filename
    attr_reader :lines
    attr_reader :mergeline

    def initialize(filename)
        @filename=filename
    end

    def add(str)
        @mergeline = str
        /([^,]*),(.*)$/ =~ str
        @newID=$1.to_i
    end

    def execute()
        lines = readFileToArray
        before, after = separate lines
        afterNew = idUpcount after

        @lines=Marshal.load(Marshal.dump(before))
        @lines.push @mergeline
        @lines += afterNew
    end

private
    def readFileToArray()
        lines = Array.new
        open(@filename, "r") do |f|
            lines = f.readlines
        end
        lines
    end

    def separate(lines)
        arrays = lines.partition do |item|
            /([^,]*),(.*)$/ =~ item
            currentID=$1.to_i
            currentID < @newID ? true: false
        end

        return arrays[0],arrays[1]
    end

    def idUpcount(array)
        result = Array.new
        array.each do |item|
            /([^,]*),(.*)$/ =~ item
            currentID=$1.to_i
            currentData=$2
            currentID+=1
            result.push currentID.to_s + ","+ currentData
        end
        result
    end

    def flush()
        open(@filename, "w") do |f|
            @lines.each do |str|
                f.write str
            end
        end
    end
end

obj = ConfigfileMerge.new ARGV[0]
obj.add("5,TEST_4,50\n")
obj.execute

obj.lines.each do |line|
    puts line
end
6
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6