SapphireSteel Software

 

  -  
     
     
     
  -  
     
     
     
  -  
     
     
     
  -  
     
     
     
  -  
     
     
     
     

 

  rss
RSS (SITE)
 
  rss
RSS (BLOG ONLY)
 
   
 
 
     

 

Section :: Ruby
- Format For Printing...

The Book Of Ruby

by Huw Collingbourne
Thursday 15 May 2008.
 

Latest update: 18th April, 2009

The Book Of Ruby is a comprehensive free tutorial to the Ruby language. It contains 425 pages in 20 chapters. It is provided in the form of a PDF document in which each chapter is accompanied by ready-to-run source code for all the examples. There is also an Introduction which explains how to use the source code in Ruby In Steel or any other editor/IDE of your choice plus appendices and an index.

The Book Of Ruby is written by Huw Collingbourne - one of the developers of the Ruby In Steel IDE.

Permissions: You may copy or distribute the text and programs of The Book Of Ruby but you may not modify them without prior consent of the author nor may you distribute the eBook in any form other than that in which it is provided. You may not print the text for redistribution. You may, however, print the chapters for your own personal use. In no circumstances may you make a charge for The Book Of Ruby or for any of its component parts.

The Book of Ruby is Copyright © 2009 Huw Collingbourne.

The Little Book Of Ruby: Note that The Book Of Ruby is an in-depth guide to Ruby. For a much simpler guide to the principal features of the Ruby language, we also have the free eBook, The Little Book Of Ruby.


DOWNLOAD

The zip file contains the latest release of The Book Of Ruby (425 pages) plus all source code.

- DOWNLOAD THE BOOK OF RUBY (2.9MB approx)


The Book Of Ruby - Table Of Contents

Introduction
- GETTING STARTED WITH RUBY

  • How To Read This Book
  • Digging Deeper
  • Making Sense Of The Text

- RUBY AND RAILS

  • What Is Ruby?
  • What Is Rails?
  • Download Ruby
  • Get The Source Code Of The Sample Programs
  • Running Ruby Programs
  • The Ruby Library Documentation

Chapter One
- STRINGS, NUMBERS, CLASSES AND OBJECTS

  • Getting and Putting Input
  • Strings and Embedded Evaluation
  • Numbers
  • Testing a Condition: if … then
  • Local and Global Variables
  • Classes and Objects
  • Instance Variables
  • Messages, Methods and Polymorphism
  • Constructors – new and initialize
  • Inspecting Objects

Chapter Two
- CLASS HIERARCHIES, ATTRIBUTES AND CLASS VARIABLES

  • Superclasses and Subclasses
  • Passing Arguments To The Superclass
  • Accessor Methods
  • ‘Set’ Accessors
  • Attribute Readers and Writers
  • Calling Methods of a Superclass
  • Class Variables
    - DIGGING DEEPER
  • Superclasses
  • Constants Inside Classes
  • Partial Classes

Chapter Three
- STRINGS AND RANGES

  • User-Defined String Delimiters
  • Backquotes
  • String Handling
    - DIGGING DEEPER
  • Ranges
  • Iterating With A Range
  • Heredocs
  • String Literals

Chapter Four
- ARRAYS AND HASHES

  • Arrays
  • Creating Arrays
  • Multi-Dimensional Arrays
  • Iterating Over Arrays
  • Indexing Into Arrays
  • Copying Arrays
  • Testing Arrays For Equality
  • Sorting Arrays
  • Comparing Values
  • Array Methods
  • Hashes
  • Creating Hashes
  • Indexing Into A Hash
  • Copying A Hash
  • Sorting A Hash
  • Hash Methods
    - DIGGING DEEPER
  • Treating Hashes As Arrays
  • Appending and Concatenating
  • Matrices and Vectors
  • Sets

Chapter Five
- LOOPS AND ITERATORS

  • For Loops
  • Multiple Iterator Arguments
  • Blocks
  • While Loops
  • While Modifiers
  • Until Loops
  • Loop
    - DIGGING DEEPER
  • The Enumerable Module
  • Custom Comparisons

Chapter Six
- CONDITIONAL STATEMENTS

  • If..Then..Else
  • And..Or..Not
  • If..Elsif
  • Unless
  • If and Unless Modifiers
  • Case Statements
  • The === Method
  • Alternative Case Syntax
    - DIGGING DEEPER
  • Boolean Conditions
  • Negation
  • Eccentricities of Boolean Operators
  • Catch and Throw

Chapter Seven
- METHODS

  • Class Methods
  • Class Variables
  • What Are Class Methods For?
  • Ruby Constructors – new or initialize?
  • Singleton Methods
  • Singleton Classes
  • Overriding Methods
  • public, private and protected
    - DIGGING DEEPER
  • Protected and Private in Descendent Classes
  • Invading The Privacy Of Private Methods
  • Singleton Class Methods
  • Nested Methods
  • Method Names

Chapter Eight
- PASSING ARGUMENTS AND RETURNING VALUES

  • Returning Values
  • Returning Multiple Values
  • Default and Multiple Arguments
  • Assignment and Parameter Passing
  • Integers Are Special
  • The One-Way-In, One-Way-Out Principle
  • Parallel Assignment
    - DIGGING DEEPER
  • By Reference Or By Value?
  • Are Assignments Copies Or References?
  • When Are Two Objects Identical?
  • Parentheses Avoid Ambiguity

Chapter Nine
- EXCEPTION HANDLING

  • Rescue
  • Ensure
  • Else
  • Error Numbers
  • Retry
  • Raise
    - DIGGING DEEPER
  • Omitting begin and end
  • catch…throw

Chapter Ten
- BLOCKS, PROCS AND LAMBDAS

  • What Is A Block?
  • Line Breaks are Significant
  • Nameless Functions
  • Looks Familiar?
  • Blocks and Arrays
  • Procs and Lambdas
  • Creating Objects From Blocks
  • What is a Closure?
  • Yield
  • Blocks Within Blocks
  • Passing Named Proc Arguments
  • Precedence Rules
  • Blocks As Iterators
    - DIGGING DEEPER
  • Returning Blocks From Methods
  • Blocks and Instance Variables
  • Blocks and Local Variables

Chapter Eleven
- SYMBOLS

  • Symbols and Strings
  • Symbols and Variables
  • Why Use Symbols?
    - DIGGING DEEPER
  • What Is A Symbol?

Chapter Twelve
- MODULES AND MIXINS

  • A Module Is Like A Class…
  • Module Methods
  • Modules as Namespaces
  • Module ‘Instance Methods’
  • Included Modules or ‘Mixins’
  • Name Conflicts
  • Alias methods
  • Mix-in With Care!
  • Including Modules From Files
    - DIGGING DEEPER
  • Modules and Classes
  • Pre-Defined Modules
  • Scope Resolution
  • Module Functions
  • Extending Objects

Chapter Thirteen
- FILES AND IO

  • Opening and Closing Files
  • Files and Directories…
  • Copying Files
  • Directory Enquiries
  • A Discursion Into Recursion
  • Sorting By Size
    - DIGGING DEEPER
  • Recursion Made Simple

Chapter Fourteen
- YAML

  • Converting To YAML
  • Nested Sequences
  • Saving YAML Data
  • Omitting Variables On Saving
  • Multiple Documents, One File
  • A YAML Database
  • Adventures in YAML
    - DIGGING DEEPER
  • A Brief Guide To YAML

Chapter Fifteen
- MARSHAL

  • Saving and Loading Data
  • Omitting Variables On Saving
  • Saving Singletons
  • YAML and Singletons
    - DIGGING DEEPER
  • Marshal Version Numbers

Chapter Sixteen
- REGULAR EXPRESSIONS

  • Making Matches
  • Match Groups
  • MatchData
  • Pre and Post Match
  • Greedy Matching
  • String methods
  • File Operations
    - DIGGING DEEPER
  • Regular Expressions

Chapter Seventeen
- THREADS

  • Creating Threads
  • Running Threads
  • The Main Thread
  • Thread Status
  • Ensuring That A Thread Executes
  • Thread Priorities
  • Mutexes
    - DIGGING DEEPER
  • Passing Execution To Other Thread

Chapter Eighteen
- DEBUGGING AND TESTING

  • IRB - Interactive Ruby
  • Debugging
  • Unit Testing
    - DIGGING DEEPER
  • Assertions Available when Unit Testing
  • Line Breaks Are Significant
  • Graphical Debuggers

Chapter Nineteen
- RUBY ON RAILS

  • First Install Rails
  • MVC – Model, View, Controller
  • A First Ruby On Rails Application
  • Create A Rails Application
  • Create A Controller
  • Can’t Find The Database?
  • Anatomy Of A Simple Rails Application
  • Create A View
  • Rails Tags
  • Let’s Make A Blog!
    - DIGGING DEEPER
  • MVC
  • The Rails Folders
  • Other Ruby Frameworks

Chapter Twenty
- DYNAMIC PROGRAMMING

  • Self-Modifying Programs
  • Eval Magic
  • Special Types of Eval
  • Adding Variables and Methods
  • Creating Classes At Runtime
  • Bindings
  • Send
  • Remove Methods
  • Handling Missing Methods
  • Writing Programs At Runtime
    - DIGGING DEEPER
  • Freezing Objects

Appendices
- APPENDIX A: DOCUMENTING RUBY WITH RDOC

- APPENDIX B: INSTALLING MYSQL FOR RUBY ON RAILS

  • Download MySQL
  • Install MySQL
  • Configure MySQL

- APPENDIX C: FURTHER READING

  • Books
  • E-Books

- APPENDIX D: WEB SITES

  • Ruby and Rails Information

- APPENDIX E: RUBY AND RAILS DEVELOPMENT SOFTWARE

  • IDEs/Editors
  • Web Servers
  • Databases

- APPENDIX F: RUBY IMPLEMENTATIONS

- INDEX

AddThis Social Bookmark Button



Forum

  • The Book Of Ruby
    23 April 2009, by ben

    Wonderful Work ever! Thanks.

  • Github repo for code examples
    21 April 2009, by timurv

    Hey guys!

    Thank you for the book.

    But one think, in the examples you does not use std ruby code style and have other errors.

    Can we create github repo with code examples and fork it? What do you think about that?

    Thanks, Timur

    • Github repo for code examples
      21 April 2009, by Huw Collingbourne

      My coding style is deliberate - not an error! ;-) - for a few of my views on coding style see here: http://www.bitwisemag.com/2/Free-425-Page-Ruby-eBook

      If you know of any actual errors please let me know and I will address them in a revision.

      You may adapt my code examples if you wish and by all means rewrite them in your preferred naming style as long as credit is given to me as the original author. The book itself is copyright, however, and the can only be distributed in its original form.

      best wishes

      Huw

  • The Book Of Ruby
    6 February 2009

    Great stuff people! I’m starting to learn Ruby as it seems like a really simple and clean language! But I hate reading long boring books so I was recommended to this site by a fellow forum member and I think the idea is great - learning from practice and toying around! That’s really cool! Great idea once again thanks and I’ll come back once I have some time to toy with and post my feedback.

  • The Book Of Ruby
    21 January 2009, by Harsh

    Thank you very much for sharing this

  • The Book Of Ruby
    29 December 2008, by cvasilak

    Thanks for sharing this! :)

    Christos

  • The Book Of Ruby
    25 November 2008
  • The Book Of Ruby
    17 July 2008, by BobMorlaix

    Great job and thanks for gracefully sharing you work! However, if I have nothing special to say about the substance, I would just have one little complaint about the form: could you please use another font for the code? Comics Sans (it’s something like that, isn’t it?) is so unpleasant (not to say awful) and unreadable! Could you not use a more classic font, such like Courier?

    Anyway, thanks again for your great job! I’m looking forward to the rest of it ;)

    • The Book Of Ruby
      17 July 2008, by Huw Collingbourne

      I remember that the font was discussed on a thread somewhere at the time of the release of The Little Book Of Ruby. Suffice to say there are two lines of thought on this - one group of people likes the ’traditional’ Courier font; others (including me) prefer Comic Sans. I decided to use Comic for the simple reason that it reminds me of the ’scripty’ fonts that used to be used in Smalltalk (I have a treasured copy of the Byte August 1981 ’Smalltalk’ special which has lots of screenshots with these types of fonts). I’m not sure why, but when I write about C# or Delphi (I have written literally hundreds of tutorials on those languages in computer magazines), Courier seems ok. When I write about Smalltalk or Ruby, I prefer to use a less formal font. I guess Courier makes me think of a console. Comic makes me think of Smalltalk’s bitmap fonts. Smalltalk has been a major influence on my own coding style in Ruby (and Smalltalk has also influenced some of the tools we’ve created - or are in the process of creating - for Ruby In Steel) which may explain why I prefer the font.

      Call it a wilful eccentricity on my part, but I’m afraid the font stays ;-)

      best wishes

      Huw

      • The Book Of Ruby
        26 August 2008, by BobMorlaix

        Well, if your choice for Comic Sans is a reference to Smalltalk, you are forgiven ;) I have been a Smalltalker for some years before switching to Java (I was forced), in the late 90s, and I understand your nostalgia about this great language. So, go for Comic Sans! :)

  • The Book Of Ruby
    8 July 2008, by Peter Mularien

    FYI this book is being offered for download here: http://rubyindia.wordpress.com/2008...

    Wanted to let you know in case you weren’t aware...

    • The Book Of Ruby
      8 July 2008, by Huw Collingbourne

      Thanks for the information. I didn’t know about that. The link on that page points back to the Zip file here so people should end up getting the latest version. That said, linking directly to the zip assumes that I won’t ever change the name of the file, which isn’t guaranteed. If anyone else wants to put up a link, I’d recommend linking to the download page rather than to the zip...

      best wishes

      Huw

  • The Book Of Ruby
    29 June 2008, by SoftMind

    Hello,

    Nice book indeed. Thanks.

    I would request you to start a blog/tutorial on Asp.Net MVC with IronRuby. You will find plenty of examples on Ruby On Rails, but a tutorial on starting out with Asp.Net MVC with IronRuby will be gr8 and a pioneer step indeed.

    I have surfed a lot on the net, but still could not get to a tutorial on the above subject. John Lam has of course a mini blog as reference.

    Since IronRuby is the way to go in future and you have always worked hard on this subject. i think you are the right person to start so that other can get a start.

    Since asp.net mvc preview 4 will support Ironruby, with Visual Web developer, it would be nice time for you to keep many things handy right now.

    Thanks

    SoftMind technology.

    • The Book Of Ruby
      30 June 2008, by Huw Collingbourne

      Thanks for the feedback. This may make a tutorial for the future. Currently we are waiting until IronRuby nears its final release before developing our IronRuby IDE more fully. At that date we shall no doubt be thinking of providing some IronRuby tutorials too ;-)

      best wishes

      Huw

  • The Book Of Ruby
    2 June 2008

    Hi,

    Thanks for helping us with a great Ruby book like this.

    Since IronRuby would be a more interesting topic, i would like you to focus more on IronRuby than Plain Ruby.

    It would be nice if you can give few examples side by side for IronRuby also. No doubt the syntax remains the same, but calling few codes from C# and implementing with IronRuby would add more mileage.

    James Hardy

    • The Book Of Ruby
      2 June 2008, by Huw Collingbourne

      In principle, if IronRuby really is fully compatible with Ruby 1.8x, then this book should be relevant to IronRuby too. In fact, as you say, there will be specific cases where there are special features of IronRuby that need extra explanation. I don’t plan to cover IronRuby in depth in this book but I will be writing articles about IronRuby development heere on the blog. We will be updating our free IronRuby IDE shortly and I’ll start blogging a bit more after that. I’ll consider the possibility of writing a more detailed guide to IronRuby - maybe a bit more like ’The Little Book Of Ruby’ (the Little Book Of IronRuby?) to supplement the information in The Book Of Ruby.

      Many thanks for your interest.

      Huw

  • The Book Of Ruby
    31 May 2008, by Pit Capitain

    I took a first short look at The Book Of Ruby, chapter 2, but I think I’ll leave it at that. I skimmed the part of accessor methods. Writing "return xxx" as the last line of a method isn’t very Rubyish. Then, it is not correct that when executing "attr_accessor :name" Ruby creates an instance variable called @name. In Ruby, instance variables are created upon the first assignment to them. This is where I stopped. I don’t know how to say it more politely, because I think it’s very generous to write a book and give it to the community for free, but before writing a Book Of Something one should be more acquainted with it.

    • The Book Of Ruby
      31 May 2008, by Huw Collingbourne

      If you wish to be absolutely literal, neither the instance variable nor the accessor method is created until a call is made to that method on an instantiated object. If you wish to verify this, take a look in the C Ruby code (eval.c, line 725 and following).

      For completeness, I will discuss Ruby’s symbol table (briefly!) in chapter 11. I tend to think that the degree of literalism which you appear to favour is unlikely to be very useful to most newcomers to Ruby, however. The actual behaviour of Ruby, from the perspective of the programmer, is that both the accessor method(s) and the variable are created when they are used (i.e. no separate declarations needed). To all intents and purposes, therefore, an accessor declaration can be thought of as a shortcut way of creating methods with matching instance variable names.

      As for your objection to ’return’ - I have never understood why some people argue that there is a definitive standard for a ‘Rubyish’ way of coding Ruby. Who decides which things are more Rubyish than others and on what grounds do they arrive at those decisions? My personal prejudice (purely to ensure maintainable code) is to avoid ambiguity whenever possible. I don’t believe that makes it ‘un-Rubyish’.

      I am not sure why you make the assertion that I am unacquainted with Ruby. That is, quite demonstrably, untrue. In the course of programming Ruby itself and also of developing our Ruby debugger and Intellisense systems over many years I can assure you that I have become very well acquainted with Ruby - both the Ruby interpreter and its Ruby and C-code sources. It is this familiarity with Ruby, and my discovery of a number of esoteric ambiguities (which we have had to deal with in our IDE), which has strongly made me favour an explicit coding style in Ruby - hence my preference for explicit returns and bracketed argument lists.

      By all means, don’t read my book. There is no obligation to do so. However, I must say that I do not understand your criticisms, nor do I consider them to be justified.

      Best wishes

      Huw

      • The Book Of Ruby
        1 June 2008, by Pit Capitain

        Huw, sorry that I upset you. As I wrote, I didn’t know how to choose better words for what I wanted to say. English is not my native language. Maybe I just had a bad day. I just wanted to mention some things I didn’t expect in a Book Of Ruby.

        Concerning accessor methods and instance variables: look at this example:

         class C
          attr_accessor :v
         end

         c = C.new
         p(c.methods - Object.methods) # => ["v", "v="]
         p(c.instance_variables) # => []

        As you can see, the accessor methods are created, but the instance variable doesn’t exist yet.

         c.v = 123
         p(c.instance_variables) # => ["@v"]

        After assignment, the instance variable finally exists. If you look again at the code in eval.c you mentioned, you can see that the methods are created indeed, but the instance variable isn’t. (BTW: this has nothing to do with symbols.) If newcomers try to access a not yet existing instance variable in their own methods, they’ll get a warning. Not very useful either.

        Concerning style: of course there is no definitive styleguide for Ruby code. But there are things that you will find in the majority of both Ruby’s standard library and in other people’s code, and using an explicit return statement at the end of a method definitely doesn’t belong to them. I didn’t say that those conventions are better or worse than your own coding style, just that they are different.

        But of course this is your book, and it is totally up to you what you make of my comments.

        • The Book Of Ruby
          2 June 2008, by Huw Collingbourne

          My approach in this book is principally to describe the behaviour of Ruby rather than its implementation. That said, I do also describe some aspects of implementation, specifically in those areas where the implementation affects the behaviour (normally this is when some kind of ambiguity is inherent in the code but is not obvious if you do not understand certain implementation details of Ruby). I don’t cover metaprogramming until chapter 20, so the creation of methods, classes and variables from symbols and strings is skated over in all the early chapters.

          The precise details of accessors and the ways in which they dynamically create methods and variables is, I think, well beyond my ambitions for chapter 2. It may be worth a more in-depth look in an article here on the site, however. I’ll consider expanding upon this shortly.

          best wishes

          Huw

        • The Book Of Ruby
          2 June 2008, by Huw Collingbourne

          By the way, there are a couple of points worth picking n in what you say...

          If newcomers try to access a not yet existing instance variable in their own methods, they’ll get a warning.

          Things are a bit more complicated than that. Consider this...

          class C
            attr_accessor :zzz                       
                 
            def abc
               puts @zzz
            end
          end

          ob = C.new
          p ob.zzz       
                  #<= nil # no warning
          p ob       
                  #<= #<C:0x2e30330>  # but no @zzz
          ob.abc
                  #<= nil # seems to indicate that @zzz is nil
          p ob
                  #<= #<C:0x27b035c> # still no @zzz (not even @zzz=nil)

          Regarding my preference for explicit returns. There are several entirely pragmatic reasons for this. This would be my preference no matter which language I was writing. One reason is that I like each piece of code to state unambiguously what it is doing. In a fully functional language this is not a problem since the behaviour of functional returns is fundamental to the language. In an object oriented language such as Ruby, however, implicit method returns break encapsulation. e.g.

          class C
            def abc( aVal )
               @myprivatevar = aVal*2
            end
          end

          ob = C.new
          x = ob.abc(100)

          Here, we may assume that the programmer of class C has intended the implementation of method abc to be entirely hidden (‘black box encapsulation’) from the world beyond the class. That is, in procedural terms, it should behave as a procedure rather than as a function. This allows the programmer to reimplement the internal behaviour of the method without any concerns that this may have any side-effects on code that uses class C. However, as we can see, some other programmer in the example above has decided to make use of the return value without the ‘consent’ of the author of class C. Who knows what side-effects that might have if C is reimplemented subsequently?

          At a bare minimum, I use ‘return’ to document those methods whose return values are intended to be accessible to the world beyond my class.

          There are, in fact, exceptions to the rule that Ruby always returns the result of the last expression evaluated. Take a setter accessor as an example:

          def abc=( aVal )
            @myprivatevar = aVal*2
          end

          Strictly speaking, if aVal is 100 we should expect this to return 200. In fact, it returns 100. this will remain so even if I add an explicit return:

          def abc=( aVal )
            return @myprivatevar = aVal*2
          end

          It still returns 100.

          I have to say that I consider Ruby’s mix of functional with OOP programming to be a bit of a problem area. In particular, my own view is that data-hiding and implementation-hiding should be fundamental features of encapsulation and that Ruby’s method-return values break this fundamental principle. I prefer the Smalltalk tradition whereby methods have explicit returns, otherwise they return the object itself.

          best wishes

          Huw

  • The Book Of Ruby
    30 May 2008

    There is a typo in your first paragraph - the sentence fragment "each of which is accompanies by read-to-run source code" should read "each of which is accompanied by read-to-run source code".

  • The Book Of Ruby
    15 May 2008, by Matt Williams

    Not to pick nits, but in your permissions statement, don’t you mean that one cannot modify the programmes "without permission" as opposed to the current "with permission"?

 

© 2009 SapphireSteel Software. All rights reserved