Fork, clone, branch (training), and bundle install.
By the end of this lesson, developers should be able to:
- Iterate through a file one line at a time.
- Explain why you should only use the block form of
File.open
. - Load data using the CSV library in order to create Ruby objects.
In Ruby, files, and all IO streams, are Enumerable.
Ruby's File includes Enumerable
(via its Parent class IO) so we
can use all of the Enumerable methods to process files a character or a line
(the default) at a time.
Other enumerable classes related to working with files include IO, mentioned above, and Dir.
We used the Ruby Standard Library class
CSV to load data
for the bin/*_array.rb
scripts in
/ga-wdi-boston/ruby-vs-js-array-methods.
Using bin/read_file.rb
we'll read all the lines in a file and print them.
Let's create a script to mimic the behavior of the wc
(word count) command
line utility in bin/word_count.rb
.
A file containing Comma Separated Values (CSV) is a simple and well supported format for data interchange, especially for tabular data.
We'll build a data loader for pets in lib/pets.rb
using the Ruby standard
library class CSV.
We'll use a lambda
- shorthand syntax ->([args]) {[code]}
, see
Proc - to ensure we use properly
formatted symbols as keys when loading data. In Ruby, lambdas verify the number
of arguments. Alternatively, we could pass a symbol from
HeaderConverters
as the value for :header_converters
in the options Hash.
Read two files at the same time using bin/read_files.rb
.
Look at Enumerator which is
what gets returned when we call each
on an open file without a block.
We'll need to look briefly at exception handling as Enumerator relies on this mechanism.
- All content is licensed under a CCBYNCSA 4.0 license.
- All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact legal@ga.co.