diff --git a/lib/csv/row.rb b/lib/csv/row.rb index 4098800..52392a2 100644 --- a/lib/csv/row.rb +++ b/lib/csv/row.rb @@ -203,7 +203,8 @@ def headers def field(header_or_index, minimum_index = 0) # locate the pair finder = (header_or_index.is_a?(Integer) || header_or_index.is_a?(Range)) ? :[] : :assoc - pair = @row[minimum_index..-1].public_send(finder, header_or_index) + # Array#[] returns nil, not [], once the offset is past the end + pair = (@row[minimum_index..-1] || []).public_send(finder, header_or_index) # return the field if we have a pair if pair.nil? @@ -572,7 +573,7 @@ def fields(*headers_and_or_indices) # row.index('Name', 3) # => nil def index(header, minimum_index = 0) # find the pair - index = headers[minimum_index..-1].index(header) + index = (headers[minimum_index..-1] || []).index(header) # return the index at the right offset, if we found one index.nil? ? nil : index + minimum_index end diff --git a/test/csv/test_row.rb b/test/csv/test_row.rb index 86ccaa1..8983614 100644 --- a/test/csv/test_row.rb +++ b/test/csv/test_row.rb @@ -73,6 +73,13 @@ def test_field assert_equal(4, @row.field("A", 3)) assert_equal(nil, @row.field("A", 4)) assert_equal(nil, @row.field("A", 5)) + + # offset past the end of the row + assert_nil(@row.field("A", 6)) + assert_nil(@row.field("A", 100)) + assert_nil(@row["A", 6]) + assert_nil(@row.index("A", 6)) + assert_equal([nil], @row.values_at(["A", 6])) end def test_fetch