Project

General

Profile

Feature #11267 » csv_field_allow_range.patch

takkanm (三村 益隆), 06/16/2015 01:12 PM

View differences:

lib/csv.rb
#
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
......
#
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] }
test/csv/test_row.rb
# 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))
test/csv/test_table.rb
@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])
    (1-1/1)