Skip to content

Commit 42dd8b7

Browse files
committed
Add Create A CSV::Table Object as a ruby til
1 parent cafb999 commit 42dd8b7

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_906 TILs and counting..._
12+
_907 TILs and counting..._
1313

1414
---
1515

@@ -691,6 +691,7 @@ _906 TILs and counting..._
691691
- [Comparing Arrays In RSpec](ruby/comparing-arrays-in-rspec.md)
692692
- [Construct A Constant From A String](ruby/construct-a-constant-from-a-string.md)
693693
- [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md)
694+
- [Create a CSV::Table Object](ruby/create-a-csv-table-object.md)
694695
- [Create A Hash From An Array Of Arrays](ruby/create-a-hash-from-an-array-of-arrays.md)
695696
- [Create Listing Of All Middleman Pages](ruby/create-listing-of-all-middleman-pages.md)
696697
- [Create Named Structs With Struct.new](ruby/create-named-structs-with-struct-new.md)

ruby/create-a-csv-table-object.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Create A CSV::Table Object
2+
3+
When you parse a file or string using `CSV.parse` (with `headers = true`) you
4+
get a [`CSV::Table`]() object in response. This object can be used to read what
5+
was in a file or it can be used to create a new file. It is also handy as a
6+
potential test object if you want to assume, but omit, file reading in a unit
7+
test.
8+
9+
You can create a `CSV::Table` one of the following two ways. First, with a file:
10+
11+
```ruby
12+
require 'csv'
13+
14+
file = # read in file
15+
csv_table = CSV.parse(file, headers: true)
16+
```
17+
18+
Second, with a string, or even better, a HEREDOC:
19+
20+
```ruby
21+
require 'csv'
22+
23+
csv_table =
24+
CSV.parse(<<-CSV, headers: true)
25+
first_name,last_name,taco
26+
Josh,Branchaud,"Al Pastor"
27+
Jake,Worth,Cauliflower
28+
CSV
29+
30+
csv_table.headers
31+
#=> ["first_name", "last_name", "taco"]
32+
```
33+
34+
From here, you can do what you need with it, whether that is using it in a test
35+
or writing it to a file.
36+
37+
[source](https://ruby-doc.org/stdlib-2.6.3/libdoc/csv/rdoc/CSV.html#class-CSV-label-CSV+with+headers)

0 commit comments

Comments
 (0)