Skip to content

Commit 7b8c3ca

Browse files
jsxs0kou
andauthored
Add CSV::TSV class for tab-separated values (#319)
GitHub: fix GH-272 This adds `CSV::TSV` that uses `\t` as the default column separator. How to use: ```ruby require "csv" # Read TSV file with default tab separator CSV::TSV.read("data.tsv") # Parse TSV string CSV::TSV.parse("a\tb\tc") # Generate TSV content CSV::TSV.generate do |tsv| tsv << ["a", "b", "c"] tsv << [1, 2, 3] end ``` Reported by kojix2. Thanks!!! --------- Co-authored-by: Sutou Kouhei <kou@cozmixng.org>
1 parent 3a7e7c7 commit 7b8c3ca

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/csv.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2129,6 +2129,12 @@ def initialize(data,
21292129
writer if @writer_options[:write_headers]
21302130
end
21312131

2132+
class TSV < CSV
2133+
def initialize(data, **options)
2134+
super(data, **({col_sep: "\t"}.merge(options)))
2135+
end
2136+
end
2137+
21322138
# :call-seq:
21332139
# csv.col_sep -> string
21342140
#

test/csv/test_tsv.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
require_relative "helper"
2+
3+
class TestTSV < Test::Unit::TestCase
4+
def test_default_separator
5+
tsv = CSV::TSV.new(String.new)
6+
assert_equal("\t", tsv.col_sep)
7+
end
8+
9+
def test_override_separator
10+
tsv = CSV::TSV.new(String.new, col_sep: ",")
11+
assert_equal(",", tsv.col_sep)
12+
end
13+
14+
def test_read_tsv_data
15+
data = "a\tb\tc\n1\t2\t3"
16+
result = CSV::TSV.parse(data)
17+
assert_equal([["a", "b", "c"], ["1", "2", "3"]], result.to_a)
18+
end
19+
20+
def test_write_tsv_data
21+
output = String.new
22+
CSV::TSV.generate(output) do |tsv|
23+
tsv << ["a", "b", "c"]
24+
tsv << ["1", "2", "3"]
25+
end
26+
assert_equal("a\tb\tc\n1\t2\t3\n", output)
27+
end
28+
29+
def test_inheritance
30+
assert_kind_of(CSV, CSV::TSV.new(String.new))
31+
end
32+
end

0 commit comments

Comments
 (0)