summaryrefslogtreecommitdiff
path: root/doc/csv/options/parsing/headers.rdoc
blob: 0ea151f24bd69a8c9d5afb747b8950980e9e4b99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
====== Option +headers+

Specifies a boolean, \Symbol, \Array, or \String to be used
to define column headers.

Default value:
  CSV::DEFAULT_OPTIONS.fetch(:headers) # => false

---

Without +headers+:
  str = <<-EOT
  Name,Count
  foo,0
  bar,1
  bax,2
  EOT
  csv = CSV.new(str)
  csv # => #<CSV io_type:StringIO encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
  csv.headers # => nil
  csv.shift # => ["Name", "Count"]

---

If set to +true+ or the \Symbol +:first_row+,
the first row of the data is treated as a row of headers:
  str = <<-EOT
  Name,Count
  foo,0
  bar,1
  bax,2
  EOT
  csv = CSV.new(str, headers: true)
  csv # => #<CSV io_type:StringIO encoding:UTF-8 lineno:2 col_sep:"," row_sep:"\n" quote_char:"\"" headers:["Name", "Count"]>
  csv.headers # => ["Name", "Count"]
  csv.shift # => #<CSV::Row "Name":"bar" "Count":"1">

---

If set to an \Array, the \Array elements are treated as headers:
  str = <<-EOT
  foo,0
  bar,1
  bax,2
  EOT
  csv = CSV.new(str, headers: ['Name', 'Count'])
  csv
  csv.headers # => ["Name", "Count"]
  csv.shift # => #<CSV::Row "Name":"bar" "Count":"1">

---

If set to a \String +str+, method <tt>CSV::parse_line(str, options)</tt> is called
with the current +options+, and the returned \Array is treated as headers:
  str = <<-EOT
  foo,0
  bar,1
  bax,2
  EOT
  csv = CSV.new(str, headers: 'Name,Count')
  csv
  csv.headers # => ["Name", "Count"]
  csv.shift # => #<CSV::Row "Name":"bar" "Count":"1">