diff options
-rw-r--r-- | ChangeLog | 5 | ||||
-rw-r--r-- | lib/csv.rb | 10 | ||||
-rwxr-xr-x | test/csv/test_row.rb | 3 | ||||
-rwxr-xr-x | test/csv/test_table.rb | 3 |
4 files changed, 18 insertions, 3 deletions
@@ -1,3 +1,8 @@ +Wed Jun 17 10:57:28 2015 SHIBATA Hiroshi <hsbt@ruby-lang.org> + + * lib/csv.rb: accept to use Range object for row selection. + [Feature #11267][ruby-dev:49091] + Wed Jun 17 09:50:12 2015 Nobuyoshi Nakada <nobu@ruby-lang.org> * lib/rdoc/servlet.rb (documentation_search, root_search): diff --git a/lib/csv.rb b/lib/csv.rb index fd493d8859..e1e151b802 100644 --- a/lib/csv.rb +++ b/lib/csv.rb @@ -284,11 +284,15 @@ class CSV # def field(header_or_index, minimum_index = 0) # locate the pair - finder = header_or_index.is_a?(Integer) ? :[] : :assoc + finder = (header_or_index.is_a?(Integer) || header_or_index.is_a?(Range)) ? :[] : :assoc pair = @row[minimum_index..-1].send(finder, header_or_index) # return the field if we have a pair - pair.nil? ? nil : pair.last + if pair.nil? + nil + else + header_or_index.is_a?(Range) ? pair.map(&:last) : pair.last + end end alias_method :[], :field @@ -690,7 +694,7 @@ class CSV # def [](index_or_header) if @mode == :row or # by index - (@mode == :col_or_row and index_or_header.is_a? Integer) + (@mode == :col_or_row and (index_or_header.is_a?(Integer) or index_or_header.is_a?(Range))) @table[index_or_header] else # by header @table.map { |row| row[index_or_header] } diff --git a/test/csv/test_row.rb b/test/csv/test_row.rb index 3acceea234..a8aeb288fc 100755 --- a/test/csv/test_row.rb +++ b/test/csv/test_row.rb @@ -64,6 +64,9 @@ class TestCSV::Row < TestCSV # by index assert_equal(3, @row.field(2)) + # by range + assert_equal([2,3], @row.field(1..2)) + # missing assert_nil(@row.field("Missing")) assert_nil(@row.field(10)) diff --git a/test/csv/test_table.rb b/test/csv/test_table.rb index 44e9d4a8be..7d2148c379 100755 --- a/test/csv/test_table.rb +++ b/test/csv/test_table.rb @@ -67,6 +67,9 @@ class TestCSV::Table < TestCSV @rows.each_index { |i| assert_equal(@rows[i], @table[i]) } assert_equal(nil, @table[100]) # empty row + # by row with Range + assert_equal([@table[1], @table[2]], @table[1..2]) + # by col @rows.first.headers.each do |header| assert_equal(@rows.map { |row| row[header] }, @table[header]) |