Writing Data
Writing to a CSV file follows a similar pattern to the CSV.foreach
method we learned about previously, except that, here, we use the CSV.open
method and supply a block.
Inside the block, we have access to the file, which we can write to by simply calling puts
on the opened csv
variable. In the same way as before, we do not need to manually call close
as the block will automatically do that for us when it exits:
require 'csv' CSV.open("new_users.csv", "w") do |csv| Â Â csv.puts ["Sarah Meyer", "25", "Cologne"] Â Â csv.puts ["Matt Hall", "35", "Sydney"] end
There is an alternative syntax that you may see other people using that works in the same way and makes use of the append
operator instead of the puts
method. We do this by using the object <<
value syntax. Really, puts
is just an alias for <<
, so you can expect it to work in the same way: