You are previewing Head First Ruby.
O'Reilly logo
Head First Ruby

Book Description

What’s all the buzz about this Ruby language? Is it right for you? Well, ask yourself: are you tired of all those extra declarations, keywords, and compilation steps in your other language? Do you want to be a more productive programmer? Then you’ll love Ruby. With this unique hands-on learning experience, you’ll discover how Ruby takes care of all the details for you, so you can simply have fun and get more done with less code.

Table of Contents

  1. Dedication
  2. Special Upgrade Offer
  3. Author of Head First Ruby
  4. How to Use This Book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. We know what your <span xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="emphasis"><em>brain</em></span> is thinking is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did
    6. Here’s what YOU can do to bend your brain into submission
    7. Read me
    8. Acknowledgments
    9. Safari<sup xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="">&#174;</sup> Books Online Books Online
  5. 1. More with Less: Code the Way You Want
    1. The Ruby philosophy
    2. Get Ruby
    3. Use Ruby
    4. Use Ruby—interactively
      1. Using the irb shell
    5. Your first Ruby expressions
    6. Math operations and comparisons
    7. Strings
    8. Variables
    9. Everything is an object!
    10. Calling a method on an object
    11. Let’s build a game
    12. Input, storage, and output
    13. Running scripts
    15. “puts” and “print”
    16. Method arguments
    17. “gets”
    18. Parentheses are optional on method calls
    19. String interpolation
    20. What’s in that string?
    21. Inspecting objects with the “inspect” and “p” methods
    22. Escape sequences in strings
      1. Commonly used escape sequences
    23. Calling “chomp” on the string object
    24. What methods are available on an object?
    25. Generating a random number
    26. Converting to strings
    27. Ruby makes working with strings easy
    28. Converting strings to numbers
      1. Common conversions
    29. Conditionals
    30. The opposite of “if” is “unless”
    31. Loops
    32. Let’s try running our game!
    33. Your Ruby Toolbox
    34. Up Next...
  6. 2. Methods and Classes: Getting Organized
    1. Defining methods
    2. Calling methods you’ve defined
    3. Method names
    4. Parameters
    5. Optional parameters
    6. Return values
      1. Implicit return values
    7. Returning from a method early
    8. Some messy methods
    9. Too many arguments
    10. Too many “if” statements
    11. Designing a class
    12. What’s the difference between a class and an object?
    13. Your first class
    14. Creating new instances (objects)
    15. Breaking up our giant methods into classes
      1. The object-oriented approach
    16. Creating instances of our new animal classes
    17. Updating our class diagram with instance methods
    18. Our objects don’t “know” their names or ages!
    19. Too many arguments (again)
    20. Local variables live until the method ends
    21. Instance variables live as long as the instance does
    22. Encapsulation
    23. Attribute accessor methods
    24. Using accessor methods
    25. Attribute writers and readers
      1. Symbols
    26. Attribute writers and readers in action
    27. Ensuring data is valid with accessors
    28. Errors—the “emergency stop” button
    29. Using “raise” in our attribute writer methods
    30. Our complete Dog class
    31. Your Ruby Toolbox
    32. Up Next...
  7. 3. Inheritance: Relying on Your Parents
    1. Copy, paste... Such a waste...
    2. Mike’s code for the virtual test-drive classes
    3. Inheritance to the rescue!
    4. Defining a superclass (requires nothing special)
    5. Defining a subclass (is really easy)
    6. Adding methods to subclasses
    7. Subclasses keep inherited methods alongside new ones
    8. Instance variables belong to the object, not the class!
    9. Overriding methods
    10. Bringing our animal classes up to date with inheritance
    11. Designing the animal class hierarchy
    12. Code for the Animal class and its subclasses
    13. Overriding a method in the Animal subclasses
    14. We need to get at the overridden method!
    15. The “super” keyword
    16. A super-powered subclass
    17. Difficulties displaying Dogs
    18. The Object class
    19. Why everything inherits from the Object class
    20. Overriding the inherited method
    21. Your Ruby Toolbox
    22. Up Next...
  8. 4. Initializing Instances: Off to a Great Start
    1. Payroll at Chargemore
    2. An Employee class
    3. Creating new Employee instances
    4. A division problem
    5. Division with Ruby’s Fixnum class
    6. Division with Ruby’s Float class
    7. Fixing the salary rounding error in Employee
    8. Formatting numbers for printing
    9. Format sequences
    10. Format sequence types
    11. Format sequence width
    12. Format sequence width with floating-point numbers
    13. Using “format” to fix our pay stubs
    14. When we forget to set an object’s attributes...
    15. “nil” stands for nothing
    16. “/” is a method
    17. The “initialize” method
    18. Employee safety with “initialize”
    19. Arguments to “initialize”
    20. Using optional parameters with “initialize”
    21. “initialize” does an end-run around our validation
    22. “initialize” and validation
    23. Call other methods on the same instance with “self”
    24. When “self” is optional
    25. Implementing hourly employees through inheritance
    26. Restoring “initialize” methods
    27. Inheritance and “initialize”
    28. “super” and “initialize”
    29. Same class, same attribute values
    30. An inefficient factory method
    31. Class methods
    32. Our complete source code
    33. Your Ruby Toolbox
    34. Up Next...
  9. 5. Arrays and Blocks: Better Than Loops
    1. Arrays
    2. Accessing arrays
    3. Arrays are objects, too!
    4. Looping over the items in an array
    5. The repeating loop
    6. Eliminating repetition...the WRONG way...
    7. Chunks of code?
    8. Blocks
      1. Blocks are mind-bending stuff. But stick with it!
    9. Defining a method that takes blocks
    10. Your first block
    11. Flow of control between a method and block
    12. Calling the same method with different blocks
    13. Calling a block multiple times
    14. Block parameters
    15. Using the “yield” keyword
    16. Block formats
    17. The “each” method
    18. The “each” method, step-by-step
    19. DRYing up our code with “each” and blocks
    20. Blocks and variable scope
    21. Using “each” with the “refund” method
    22. Using “each” with our last method
    23. Our complete invoicing methods
    24. We’ve gotten rid of the repetitive loop code!
    25. Utilities and appliances, blocks and methods
    26. Your Ruby Toolbox
    27. Up Next...
  10. 6. Block Return Values: How Should I Handle This?
    1. A big collection of words to search through
    2. Opening the file
    3. Safely closing the file
    4. Safely closing the file, with a block
    5. Don’t forget about variable scope!
    6. Finding array elements we want, with a block
    7. The verbose way to find array elements, using “each”
    8. Introducing a faster method...
    9. Blocks have a return value
    10. How the method uses a block return value
    11. Putting it all together
    12. A closer look at the block return values
    13. Eliminating elements we don’t want, with a block
    14. The return values for “reject”
    15. Breaking a string into an array of words
    16. Finding the index of an array element
    17. Making one array that’s based on another, the hard way
    18. Making one array based on another, using “map”
    19. Some additional logic in the “map” block body
    20. The finished product
    21. Your Ruby Toolbox
    22. Up Next...
  11. 7. Hashes: Labeling Data
    1. Counting votes
    2. An array of not ideal
    3. Hashes
    4. Hashes are objects
    5. Hashes return “nil” by default
    6. nil (and only nil) is “falsy”
    7. Returning something other than “nil” by default
    8. Normalizing hash keys
    9. Hashes and “each”
    10. A mess of method arguments
    11. Using hashes as method parameters
    12. Hash parameters in our Candidate class
    13. Leave off the braces!
    14. Leave out the arrows!
    15. Making the entire hash optional
    16. Typos in hash arguments are dangerous
    17. Keyword arguments
    18. Using keyword arguments with our Candidate class
    19. Required keyword arguments
    20. Your Ruby Toolbox
    21. Up Next...
  12. 8. References: Crossed Signals
    1. Some confusing bugs
    2. The heap
    3. References
    4. When references go wrong
    5. Aliasing
    6. Fixing the astronomer’s program
    7. Quickly identifying objects with “inspect”
    8. Problems with a hash default object
    9. We’re actually modifying the hash default object!
    10. A more detailed look at hash default objects
    11. Back to the hash of planets and moons
    12. Our wish list for hash defaults
    13. Hash default blocks
    14. Hash default blocks: Assigning to the hash
    15. Hash default blocks: Block return value
    16. Hash default blocks: A shortcut
    17. The astronomer’s hash: Our final code
    18. Using hash default objects safely
    19. Hash default object rule #1: Don’t modify the default object
    20. Hash default object rule #2: Assign values to the hash
    21. The rule of thumb for hash defaults
    22. Your Ruby Toolbox
    23. Up Next...
  13. 9. Mixins: Mix It Up
    1. The media-sharing app
    2. The media-sharing app...using inheritance
    3. One of these classes is not (quite) like the others
    4. Option one: Make Photo a subclass of Clip
    5. Option two: Copy the methods you want into the Photo class
    6. Not an option: Multiple inheritance
    7. Using modules as mixins
    8. Mixins, behind the scenes
    9. Creating a mixin for comments
    10. Using our comments mixin
    11. A closer look at the revised “comments” method
    12. Why you shouldn’t add “initialize” to a mixin
    13. Mixins and method overriding
    14. Avoid using “initialize” methods in modules
    15. Using the Boolean “or” operator for assignment
    16. The conditional assignment operator
    17. Our complete code
    18. Your Ruby Toolbox
    19. Up Next...
  14. 10. Comparable and Enumerable: Ready-Made Mixes
    1. Mixins built into Ruby
    2. A preview of the Comparable mixin
    3. Choice (of) beef
    4. Implementing a greater-than method on the Steak class
    5. Constants
    6. We have a lot more methods to define...
    7. The Comparable mixin
    8. The spaceship operator
    9. Implementing the spaceship operator on Steak
    10. Mixing Comparable into Steak
    11. How the Comparable methods work
    12. Our next mixin
    13. The Enumerable module
    14. A class to mix Enumerable into
    15. Mixing Enumerable into our class
    16. Inside the Enumerable module
    17. Your Ruby Toolbox
    18. Up Next...
  15. 11. Documentation: Read the Manual
    1. Learning how to learn more
    2. Ruby’s core classes and modules
    3. Documentation
    4. HTML documentation
    5. Listing available classes and modules
    6. Looking up instance methods
    7. Instance methods denoted with # in the docs
    8. Instance method documentation
    9. Arguments in call signatures
    10. Blocks in call signatures
    11. Read the docs for the superclass and mixins, too!
    12. Read the docs for the superclass and mixins, too! (continued)
    13. Pool Puzzle
    14. Pool Puzzle Solution
    15. Looking up class methods
    16. Class method documentation
    17. Docs for a class that doesn’t exist?!
    18. The Ruby standard library
    19. Looking up classes and modules in the standard library
    20. Where Ruby docs come from: rdoc
    21. What rdoc can deduce about your classes
    22. Adding your own documentation, with comments
    23. The “initialize” instance method appears as the “new” class method
    24. Your Ruby Toolbox
    25. Up Next...
  16. 12. Exceptions: Handling the Unexpected
    1. Don’t use method return values for error messages
    2. Using “raise” to report errors
    3. Using “raise” by itself creates new problems
    4. Exceptions: When something’s gone wrong
    5. Rescue clauses: A chance to fix the problem
    6. Ruby’s search for a rescue clause
    7. Using a rescue clause with our SmallOven class
    8. We need a description of the problem from its source
    9. Exception messages
    10. Our code so far...
    11. Different rescue logic for different exceptions
    12. Exception classes
    13. Specifying exception class for a rescue clause
    14. Multiple rescue clauses in one begin/end block
    15. Updating our oven code with custom exception classes
    16. Trying again after an error with “retry”
    17. Updating our oven code with “retry”
    18. Things you want to do <span xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="underline">no matter what</span>
    19. The ensure clause
    20. Ensuring the oven gets turned off
    21. Your Ruby Toolbox
    22. Up Next...
  17. 13. Unit Testing: Code Quality Assurance
    1. Automated tests find your bugs before someone else does
    2. A program we <span xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="underline">should</span> have had automated tests for have had automated tests for
    3. Types of automated tests
    4. MiniTest: Ruby’s standard unit-testing library
    5. Running a test
    6. Testing a class
    7. A closer look at the test code
    8. Red, green, refactor
    9. Tests for ListWithCommas
    10. Getting the test to pass
    11. Another bug to fix
    12. Test failure messages
    13. A better way to assert that two values are equal
    14. Some other assertion methods
    15. Removing duplicated code from your tests
    16. The “setup” method
    17. The “teardown” method
    18. Updating our code to use the “setup” method
    19. Your Ruby Toolbox
    20. Up Next...
  18. 14. Web Apps: Serving HTML
    1. Writing web apps in Ruby
    2. Our task list
    3. Project directory structure
    4. Browsers, requests, servers, and responses
    5. Sinatra takes requests
    6. Downloading and installing libraries with RubyGems
    7. Installing the Sinatra gem
    8. A simple Sinatra app
    9. Your computer is talking to itself
    10. Request type
    11. Resource path
    12. Sinatra routes
    13. Multiple routes in the same Sinatra app
    14. A route for the list of movies
    15. Making a movie list in HTML
    16. Accessing the HTML from Sinatra
    17. A class to hold our movie data
    18. Setting up a Movie object in the Sinatra app
    19. ERB embedding tags
    20. The ERB output embedding tag
    21. Embedding a movie title in our HTML
    22. Pool Puzzle
    23. Pool Puzzle Solution
    24. The regular embedding tag
    25. Looping over several movie titles in our HTML
    26. Letting users add data with HTML forms
    27. Getting an HTML form for adding a movie
    28. HTML tables
    29. Cleaning up our form with an HTML table
    30. There’s still more to do
    31. Your Ruby Toolbox
    32. Up Next...
  19. 15. Saving and Loading Data: Keep It Around
    1. Saving and retrieving form data
    2. Our browser can GET the form...
    3. ... But it needs to POST the response
    4. Setting the HTML form to send a POST request
    5. Setting up a Sinatra route for a POST request
    6. Converting objects to and from strings with YAML
    7. Saving objects to a file with YAML::Store
    8. Saving movies to a file with YAML::Store
    9. A system for finding Movies in the YAML::Store
    10. Numeric IDs for Movies
    11. Finding the next available movie ID
    12. A class to manage our YAML::Store
    13. Using our MovieStore class in the Sinatra app
    14. Testing the MovieStore
    15. Loading all movies from the MovieStore
    16. Loading all movies from the MovieStore (continued)
    17. Loading all movies in the Sinatra app
    18. Building HTML links to individual movies
    19. Building HTML links to individual movies (continued)
    20. Named parameters in Sinatra routes
    21. Using a named parameter to get a movie’s ID
    22. Defining routes in order of priority
    23. Finding a Movie in the YAML::Store
    24. An ERB template for an individual movie
    25. Finishing the Sinatra route for individual movies
    26. Let’s try it all out!
    27. Our complete app code
    28. Your Ruby Toolbox
    29. Up Next...
  20. A. Leftovers: The top ten topics (we didn’t cover)
    1. #1 Other cool libraries
      1. Ruby on Rails
      2. dRuby
      3. CSV
    2. #2 Inline if and unless
    3. #3 Private methods
    4. #4 Command-line arguments
    5. #5 Regular expressions
    6. #6 Singleton methods
    7. #7 Call any method, even undefined ones
    8. #7 Call any method, even undefined ones (continued)
    9. #8 Automating tasks with Rake
    10. #9 Bundler
    11. #10 Other books
  21. B. This isn’t goodbye
  22. C. O’reilly<sup xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="">&#174;</sup>: Ruby: Ruby
    1. What will you learn from this book?
    2. What’s so special about this book?
  23. Index
  24. About the Author
  25. Special Upgrade Offer
  26. Copyright