The Book of Ruby
Total Page:16
File Type:pdf, Size:1020Kb
THE BOOK OF RUBY HUW COLLINGBOURNE THE BOOK OF RUBY Copyright © 2009 Huw Collingbourne The right of Huw Collingbourne to be identified as the Author of the Work has been asserted by him in accordance with the Copyright, Designs and Patents Act 1988. All rights reserved. No part of this publication may be reproduced, stored in a re- trieval system, or transmitted in any form or by any means without the prior writ- ten permission of the publisher, nor be otherwise circulated in any form of binding or cover other than that in which it is published and without a similar condition be- ing imposed on the subsequent purchaser. Author’s web site: http://www.sapphiresteel.com/ ABOUT THE AUTHOR ABOUT THE AUTHOR Huw Collingbourne is Technology Director of SapphireSteel Software (http://www.sapphiresteel.com/), developers of the ‘Ruby In Steel’ Ruby and Rails IDE for Visual Studio and the ‘Amethyst’ IDE for Adobe Flex. Huw is a well known technology writer in the UK and has written numerous opinion and programming columns, including tutorials on C#, Delphi, Java, Smalltalk and Ruby for a number of computer magazines such as Computer Shopper, PC Pro and PC Plus. He is author of the free ebook, The Little Book Of Ruby, and is the editor the online computing magazine, Bitwise (www.bitwisemag.com). Huw has an MA in English from the University of Cambridge. THE BOOK OF RUBY INTRODUCTION Getting Started With Ruby As you are now reading a book on Ruby, I think it is safe to work on the assump- tion that you don’t need me to persuade you of the merits of the Ruby language. Instead I’ll take the somewhat unconventional step of starting with a warning: many people are attracted to Ruby by its simple syntax and its ease of use. They are wrong. Ruby’s syntax may look simple at first sight but, the more you get to know the language the more you will realize that it is, on the contrary, extremely complex. The plain fact of the matter is that Ruby has a number of pitfalls just waiting for unwary programmers to drop into. In this book it is my aim to guide you safely over the pitfalls and lead you through the choppy waters of Ruby’s syntax and class libraries. In the process, I’ll be exploring both the smooth, well-paved highways and the gnarlier, bumpy little byways of Ruby. By the end of the journey, you should be able to use Ruby safely and effectively without getting caught out by any unexpected hazards along the way. The Book Of Ruby concentrates principally on version 1.8.x of the Ruby lan- guage. While a version 1.9 of Ruby has been released, Ruby 1.8 is still far more widely used. Ruby 1.9 may be regarded as a stepping stone towards Ruby 2.0. In most respects the syntax of Ruby 1.9 is close to that of Ruby 1.8 but you should be aware that there are some differences and complete compatibility is not guaranteed. i THE BOOK OF RUBY HOW TO READ THIS BOOK The book is divided up into bite-sized chunks. Each chapter introduces a theme which is subdivided into sub-topics. Each programming topic is accompanied by one or more small self-contained, ready-to-run Ruby programs. If you want to follow a well-structured ‘course’, read each chapter in sequence. If you prefer a more hands-on approach, you can run the programs first and refer to the text when you need an explanation. If you already have some experience of Ruby, feel free to cherry-pick topics in any order that you find useful. There are no monolithic applications in this book so you don’t have to worry that you might ‘lose the plot’ if you read the chapters out of order! DIGGING DEEPER Every chapter apart from the first includes a section called ‘Digging Deeper’. This is where we explore specific aspects of Ruby (including a few of those gnarly byways I mentioned a moment ago) in greater depth. In many cases you could skip the Digging Deeper sections and still learn all the Ruby you will ever need. On the other hand, it is in the Digging Deeper sections that we often get closest to the inner workings of Ruby so, if you skip them, you are going to miss out on some pretty interesting stuff. MAKING SENSE OF THE TEXT In The Book Of Ruby, any Ruby source code is written like this: def saysomething puts( "Hello" ) end When there is a sample program to accompany the code, the program name is shown in a box on the right-hand side of the page, like this: helloname.rb ii INTRODUCTION Explanatory notes (which generally provide some hints or give a more in-depth explanation of some point mentioned in the text) are shown in a box like this: This is an explanatory note. You can skip it if you like – but if you do so, you may miss something of interest<! iii THE BOOK OF RUBY Ruby and Rails WHAT IS RUBY? Ruby is a cross-platform interpreted language which has many features in common with other ‘scripting’ languages such as Perl and Python. It has an ‘English language’ style syntax which looks somewhat Pascal-like at first sight. It is thoroughly object oriented, and has a good deal in common with the great- granddaddy of ‘pure’ OO languages, Smalltalk. It has been said that the lan- guages which most influenced the development of Ruby were: Perl, Smalltalk, Eiffel, Ada and Lisp. The Ruby language was created by Yukihiro Matsumoto (commonly known as ‘Matz’) and it was first released in 1995. WHAT IS RAILS? Currently much of the excitement surrounding Ruby can be attributed to a web development framework called Rails – popularly known as ‘Ruby On Rails’. Rails is an impressive framework but it is not the be-all and end-all of Ruby. Indeed, if you were to leap right into Rails development without first mastering Ruby, you might find that you end up creating applications that you don’t even understand (this is, in fact, all too common among Ruby On Rails novices). Understanding Ruby is a necessary prerequisite of understanding Rails. DOWNLOAD RUBY You can download the latest version of Ruby from http://www.ruby-lang.org. Be sure to download the binaries (not merely the source code). On a PC you can install Ruby using the Ruby Installer for Windows: http://rubyinstaller.rubyforge.org/wiki/wiki.pl Alternatively, if you are using the Ruby In Steel IDE, you can install Ruby, Rails, Ruby In Steel and all the other tools you will need using the Ruby In Steel ‘All-in- one installer’ available on the site’s Download page: http://www.sapphiresteel.com/ iv INTRODUCTION GET THE SOURCE CODE OF THE SAMPLE PROGRAMS All the programs in every chapter in this book are available for download as a Zip archive from http://www.sapphiresteel.com/The-Book-Of-Ruby. When you unzip the programs you will find that they are grouped into a set of directories – one for each chapter. For the benefit of programmers using Ruby In Steel (the Visual Studio IDE developed by the author of this book’s company), you will be able to load the programs as Visual Studio solutions into Ruby In Steel For Visual Studio 2008, with the programs for each chapter arranged on the branches of a tree in the Project Manager. If you are using another editor or IDE, load each Ruby program, one by one, as it is needed. Users of Ruby In Steel for Visual Studio 2005 may import or convert the projects (via the File New/Open menu). RUNNING RUBY PROGRAMS It is often useful to keep a command window open in the source directory containing your Ruby program files. Assuming that the Ruby interpreter is correctly pathed on your system, you will then be able to run programs by entering ruby <program name> like this: ruby 1helloworld.rb If you are using Ruby In Steel you can run the programs in the interactive console by pressing CTRL+F5 or run them in the debugger by pressing F5. THE RUBY LIBRARY DOCUMENTATION The Book Of Ruby covers many of the classes and methods in the standard Ruby library - but by no means all of them! At some stage, therefore, you will need to refer to documentation on the full range of classes used by Ruby. Fortunately, the Ruby class library contains embedded documentation which has been extracted and compiled into an easily browsable reference which is available in several formats. For example, refer to this online documentation which is shown in a multi-pane web page: http://www.ruby-doc.org/core/ v THE BOOK OF RUBY Alternatively, here you can browse the library alphabetically: http://www.ruby-doc.org/stdlib/ The above page contains instructions for downloading the documentation for offline browsing. There is also a page from which the library (and other) docu- mentation may be downloaded in various formats, versions and languages: http://www.ruby-doc.org/downloads OK, that’s enough of the preamble – let’s get down to work. Time to move straight on to Chapter One< vi INTRODUCTION The Book Of Ruby is sponsored by SapphireSteel Software, makers of the Ruby In Steel IDE for Visual Studio. http://www.sapphiresteel.com vii CHAPTER ONE Strings, Numbers, Classes and Objects The first thing to know about the Ruby language is that it’s easy to use.