Book Image

The Ruby Workshop

By : Akshat Paul, Peter Philips, Dániel Szabó, Cheyne Wallace
Book Image

The Ruby Workshop

By: Akshat Paul, Peter Philips, Dániel Szabó, Cheyne Wallace

Overview of this book

The beauty of Ruby is its readability and expressiveness. Ruby hides away a lot of the complexity of programming, allowing you to work quickly and 'do more' with fewer lines of code. This makes it a great programming language for beginners, but learning any new skill can still be a daunting task. If you want to learn to code using Ruby, but don't know where to start, The Ruby Workshop will help you cut through the noise and make sense of this fun, flexible language. You'll start by writing and running simple code snippets and Ruby source code files. After learning about strings, numbers, and booleans, you'll see how to store collections of objects with arrays and hashes. You'll then learn how to control the flow of a Ruby program using boolean logic. The book then delves into OOP and explains inheritance, encapsulation, and polymorphism. Gradually, you'll build your knowledge of advanced concepts by learning how to interact with external APIs, before finally exploring the most popular Ruby framework ? Ruby on Rails ? and using it for web development. Throughout this book, you'll work on a series of realistic projects, including simple games, a voting application, and an online blog. By the end of this Ruby book, you'll have the knowledge, skills and confidence to creatively tackle your own ambitious projects with Ruby.
Table of Contents (14 chapters)

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:

...