класс CSV::Row
Строка CSV::Row — это часть Array и часть Hash. Она сохраняет порядок полей и допускает дубликаты, как и в Array, но также позволяет получать доступ к полям по имени, как если бы они были в Hash.
Все строки, возвращаемые CSV, будут созданы из этого класса, если обработка строки заголовков включена.
Атрибуты
Внутренний формат данных, используемый для сравнения на равенство.
Общедоступные методы класса
# File lib/csv/row.rb, line 30
def initialize(headers, fields, header_row = false)
@header_row = header_row
headers.each { |h| h.freeze if h.is_a? String }
# handle extra headers or fields
@row = if headers.size >= fields.size
headers.zip(fields)
else
fields.zip(headers).each(&:reverse!)
end
end Создаёт новую строку CSV::Row из headers и fields, которые должны быть массивами. Если один массив короче другого, он будет заполнен объектами nil.
Необязательный параметр header_row может быть установлен в true для обозначения, с помощью CSV::Row.header_row?() и CSV::Row.field_row?(), что это строка заголовков. В противном случае строка предполагается строкой данных.
Объект CSV::Row поддерживает следующие методы Array через делегирование:
-
empty?()
-
length()
-
size()
Методы публичного экземпляра
# File lib/csv/row.rb, line 181
def <<(arg)
if arg.is_a?(Array) and arg.size == 2 # appending a header and name
@row << arg
elsif arg.is_a?(Hash) # append header and name pairs
arg.each { |pair| @row << pair }
else # append field value
@row << [nil, arg]
end
self # for chaining
end Если предоставлен двухэлементный Array, он предполагается как заголовок и поле, и пара добавляется. Hash работает аналогично, причём ключ является заголовком, а значение — полем. Всё остальное предполагается как одиночное поле, которое добавляется с заголовком nil.
Этот метод возвращает строку для цепочки вызовов.
# File lib/csv/row.rb, line 322 def ==(other) return @row == other.row if other.is_a? CSV::Row @row == other end
Возвращает true, если эта строка содержит те же заголовки и поля в том же порядке, что и other.
# File lib/csv/row.rb, line 148
def []=(*args)
value = args.pop
if args.first.is_a? Integer
if @row[args.first].nil? # extending past the end with index
@row[args.first] = [nil, value]
@row.map! { |pair| pair.nil? ? [nil, nil] : pair }
else # normal index assignment
@row[args.first][1] = value
end
else
index = index(*args)
if index.nil? # appending a field
self << [args.first, value]
else # normal header assignment
@row[index][1] = value
end
end
end Ищет поле по семантике, описанной в CSV::Row.field(), и присваивает value.
Присвоение за пределами строки с использованием индекса установит все пары между значениями по умолчанию [nil, nil]. Присвоение несуществующему заголовку добавит новую пару.
# File lib/csv/row.rb, line 216
def delete(header_or_index, minimum_index = 0)
if header_or_index.is_a? Integer # by index
@row.delete_at(header_or_index)
elsif i = index(header_or_index, minimum_index) # by header
@row.delete_at(i)
else
[ ]
end
end Удаляет пару из строки по header или index. Пара находится как описано в CSV::Row.field(). Удаленная пара возвращается, или nil если пара не найдена.
# File lib/csv/row.rb, line 235
def delete_if(&block)
return enum_for(__method__) { size } unless block_given?
@row.delete_if(&block)
self # for chaining
end Предоставленный block получает заголовок и поле для каждой пары в строке и ожидается, что вернёт true или false, в зависимости от того, должна ли пара быть удалена.
Этот метод возвращает строку для цепочки вызовов.
Если блок не указан, возвращается Enumerator.
# File lib/csv/row.rb, line 356
def dig(index_or_header, *indexes)
value = field(index_or_header)
if value.nil?
nil
elsif indexes.empty?
value
else
unless value.respond_to?(:dig)
raise TypeError, "#{value.class} does not have \#dig method"
end
value.dig(*indexes)
end
end Извлекает вложенное значение, заданное последовательностью index или header объектов, вызывая dig на каждом шаге, возвращая nil, если любой промежуточный шаг равен nil.
# File lib/csv/row.rb, line 308
def each(&block)
return enum_for(__method__) { size } unless block_given?
@row.each(&block)
self # for chaining
end Возвращает каждую пару строки как кортеж заголовка и поля (похоже на итерацию по Hash). Этот метод возвращает строку для цепочки вызовов.
Если блок не указан, возвращается Enumerator.
Поддержка Enumerable.
# File lib/csv/row.rb, line 110
def fetch(header, *varargs)
raise ArgumentError, "Too many arguments" if varargs.length > 1
pair = @row.assoc(header)
if pair
pair.last
else
if block_given?
yield header
elsif varargs.empty?
raise KeyError, "key not found: #{header}"
else
varargs.first
end
end
end Этот метод извлекает значение поля по header. Он имеет такое же поведение, как и Hash#fetch: если есть поле с данным header, возвращается его значение. В противном случае, если задан блок, он передаёт header в него, и результат блока возвращается; если в качестве второго аргумента задано default, оно возвращается; в противном случае возбуждается KeyError.
# File lib/csv/row.rb, line 84
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].send(finder, header_or_index)
# return the field if we have a pair
if pair.nil?
nil
else
header_or_index.is_a?(Range) ? pair.map(&:last) : pair.last
end
end Этот метод вернёт значение поля по header или index. Если поле не найдено, возвращается nil.
Когда предоставлен offset, гарантируется, что совпадение заголовка происходит на или после offset индекса. Это можно использовать для поиска дубликатов заголовков, без привязки к точным индексам.
# File lib/csv/row.rb, line 294 def field?(data) fields.include? data end
Возвращает true, если data соответствует полю в этой строке, и false в противном случае.
# File lib/csv/row.rb, line 62 def field_row? not header_row? end
Возвращает true, если это строка поля.
# File lib/csv/row.rb, line 251
def fields(*headers_and_or_indices)
if headers_and_or_indices.empty? # return all fields--no arguments
@row.map(&:last)
else # or work like values_at()
all = []
headers_and_or_indices.each do |h_or_i|
if h_or_i.is_a? Range
index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
index(h_or_i.begin)
index_end = h_or_i.end.is_a?(Integer) ? h_or_i.end :
index(h_or_i.end)
new_range = h_or_i.exclude_end? ? (index_begin...index_end) :
(index_begin..index_end)
all.concat(fields.values_at(new_range))
else
all << field(*Array(h_or_i))
end
end
return all
end
end Этот метод принимает любое количество аргументов, которые могут быть заголовками, индексами, диапазонами того или другого, или двухэлементными массивами, содержащими заголовок и смещение. Каждый аргумент будет заменён на поиск поля, как описано в CSV::Row.field().
Если вызван без аргументов, возвращаются все поля.
# File lib/csv/row.rb, line 127 def has_key?(header) !!@row.assoc(header) end
Возвращает true, если есть поле с данным header.
# File lib/csv/row.rb, line 57 def header_row? @header_row end
Возвращает true, если это строка заголовка.
# File lib/csv/row.rb, line 67 def headers @row.map(&:first) end
Возвращает заголовки этой строки.
# File lib/csv/row.rb, line 283 def index(header, minimum_index = 0) # find the pair 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
Этот метод вернёт индекс поля с указанным header. offset можно использовать для поиска дубликатов имён заголовков, как описано в CSV::Row.field().
# File lib/csv/row.rb, line 51 def initialize_copy(other) super @row = @row.dup end
# File lib/csv/row.rb, line 373
def inspect
str = ["#<", self.class.to_s]
each do |header, field|
str << " " << (header.is_a?(Symbol) ? header.to_s : header.inspect) <<
":" << field.inspect
end
str << ">"
begin
str.join('')
rescue # any encoding error
str.map do |s|
e = Encoding::Converter.asciicompat_encoding(s.encoding)
e ? s.encode(e) : s.force_encoding("ASCII-8BIT")
end.join('')
end
end Краткое описание полей, сгруппированных по заголовкам, в формате ASCII-совместимого String.
# File lib/csv/row.rb, line 200
def push(*args)
args.each { |arg| self << arg }
self # for chaining
end Сокращение для добавления нескольких полей. Эквивалентно:
args.each { |arg| csv_row << arg }
Этот метод возвращает строку для цепочки вызовов.
# File lib/csv/row.rb, line 347 def to_csv(**options) fields.to_csv(**options) end
Возвращает строку в формате CSV String. Заголовки не используются. Эквивалентно:
csv_row.fields.to_csv( options )
# File lib/csv/row.rb, line 331
def to_h
hash = {}
each do |key, _value|
hash[key] = self[key] unless hash.key?(key)
end
hash
end Преобразует строку в простой Hash. Обратите внимание, что порядок полей будет потерян, а дублирующие поля будут перезаписаны.
Ruby Core © 1993–2017 Yukihiro Matsumoto
Licensed under the Ruby License.
Ruby Standard Library © contributors
Licensed under their own licenses.