Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Ruby Workshop

You're reading from   The Ruby Workshop Develop powerful applications by writing clean, expressive code with Ruby and Ruby on Rails

Arrow left icon
Product type Paperback
Published in Oct 2019
Publisher Packt
ISBN-13 9781838642365
Length 544 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (4):
Arrow left icon
Dániel Szabó Dániel Szabó
Author Profile Icon Dániel Szabó
Dániel Szabó
Akshat Paul Akshat Paul
Author Profile Icon Akshat Paul
Akshat Paul
Peter Philips Peter Philips
Author Profile Icon Peter Philips
Peter Philips
Cheyne Wallace Cheyne Wallace
Author Profile Icon Cheyne Wallace
Cheyne Wallace
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Writing and Running Ruby Programs 2. Ruby Data Types and Operations FREE CHAPTER 3. Program Flow Ruby Methods 5. Object-Oriented programming with Ruby 6. Modules and Mixins 7. Introduction to Ruby Gems 8. Debugging with Ruby 9. Ruby Beyond the Basics l 10. Ruby Beyond the Basics ll 11. Introduction to Ruby on Rails l 12. Introduction to Ruby on Rails ll Appendix

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:

...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at R$50/month. Cancel anytime