Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/csv/row.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions test/csv/test_row.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down