Last active
August 18, 2017 01:40
-
-
Save tomoyamkung/6101878 to your computer and use it in GitHub Desktop.
[Ruby]Arrayをファイルに書き出すモジュール
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! ruby | |
#-*- encoding: utf-8 -*- | |
module FileWriter | |
LINEFEED_CODE_LF = "\n" | |
def write(path, content, linefeed_code = nil) | |
file = File.open(path, "w") | |
content.each do |line| | |
if linefeed_code == nil | |
file.write(line) | |
else | |
file.write(line + linefeed_code) | |
end | |
end | |
file.close | |
end | |
end | |
if __FILE__ == $0 | |
require 'test/unit' | |
require './array-to-tempfile' | |
class FileWriterTest < Test::Unit::TestCase | |
include FileWriter | |
include ArrayToTempfile | |
def test_write | |
content = ["line1", "line2", "line3"] | |
path = get_tempfile_path | |
write(path, content) | |
File.open(path, "r") do |file| | |
file.each do |line| | |
assert_equal(content.join, line) | |
end | |
end | |
end | |
def test_write_with_linefeed_code | |
content = ["line1", "line2", "line3"] | |
path = get_tempfile_path | |
write(path, content, FileWriter::LINEFEED_CODE_LF) | |
File.open(path, "r") do |file| | |
file.each_with_index do |line, index| | |
assert_equal(content[index] + FileWriter::LINEFEED_CODE_LF, line) | |
end | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! ruby | |
#-*- encoding: utf-8 -*- | |
module ArrayToTempfile | |
require 'tempfile' | |
def write_array_to_tempfile(array) | |
@tempfile = Tempfile.new("hoge") if @tempfile == nil | |
array.each do |line| | |
@tempfile.puts(line) | |
end | |
@tempfile.close | |
end | |
def get_tempfile_path | |
@tempfile = Tempfile.new("hoge") if @tempfile == nil | |
return @tempfile.path | |
end | |
def delete_tempfile | |
@tempfile.unlink | |
end | |
def flush | |
@tempfile.close | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment