PDF Head First Ruby A Brain Friendly Guide 1st Edition Mcgavren download
PDF Head First Ruby A Brain Friendly Guide 1st Edition Mcgavren download
com
https://ebookname.com/product/head-first-ruby-a-brain-
friendly-guide-1st-edition-mcgavren/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/head-first-android-development-a-brain-
friendly-guide-2nd-edition-edition-griffiths/
ebookname.com
https://ebookname.com/product/head-first-excel-a-learner-s-guide-to-
spreadsheets-head-first-guides-1st-edition-michael-milton/
ebookname.com
https://ebookname.com/product/the-complete-workbook-for-science-fair-
projects-1st-edition-julianne-blair-bochinski/
ebookname.com
Handbook of Competence and Motivation Theory and
Application 2nd Edition Andrew J. Elliot
https://ebookname.com/product/handbook-of-competence-and-motivation-
theory-and-application-2nd-edition-andrew-j-elliot/
ebookname.com
https://ebookname.com/product/theory-of-machines-kinematics-and-
dynamics-2nd-edition-b-v-r-gupta/
ebookname.com
https://ebookname.com/product/vibrational-spectroscopy-of-biological-
and-polymeric-materials-1st-edition-vasilis-g-gregoriou/
ebookname.com
https://ebookname.com/product/where-the-wild-frontiers-are-3-print-
edition-manan-ahmed/
ebookname.com
https://ebookname.com/product/strategic-marketing-planning-and-
control-second-edition-marketing-series-london-england-student-graeme-
drummond/
ebookname.com
Head First
Ruby
Wouldn’t it be dreamy if
there were a book on Ruby that
didn’t throw blocks, modules, and
exceptions at you all at once? I
guess it’s just a fantasy…
Jay McGavren
Boston
Head First Ruby
by Jay McGavren
Printing History:
November 2015: First Edition.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Head First series designations,
Head First Ruby, and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and the author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
Code for this book was developed using 100% recycled electrons.
ISBN: 978-1-449-37265-1
[LSI] [2015-12-11]
To open source software creators everywhere.
You make all of our lives better.
the author
Jay McGavren
iv intro
table of contents
v
table of contents
1
Code the Way You Want
You’re wondering what this crazy Ruby language is all about,
nd if it’s right for you. Let us ask you this: Do you like being productive? Do you feel
a
like all those extra compilers and libraries and class files and keystrokes in your other
language bring you closer to a finished product, admiring coworkers, and happy
customers? Would you like a language that takes care of the details for you? If you
sometimes wish you could stop maintaining boilerplate code and get to work on your
problem, then Ruby is for you. Ruby lets you get more done with less code.
The Ruby philosophy 2
Use Ruby—interactively 5
Your first Ruby expressions 6
Math operations and comparisons 6
Strings 6
Variables 7
Calling a method on an object 8
Input, storage, and output 12
Running scripts 13
Comments 14
“puts” and “print” 14
Method arguments 15
“gets” 15
String interpolation 16
Inspecting objects with the “inspect” and “p” methods 18
Escape sequences in strings 19
Calling “chomp” on the string object 20
Generating a random number 22
Converting to strings 23
Converting strings to numbers 25
Conditionals 26
The opposite of “if ” is “unless” 29
Loops 30
The comput
Source code Your Ruby Toolbox 34
executes youer
program. r
2
Getting Organized
You’ve been missing out.You’ve been calling methods and creating objects
like a pro. But the only methods you could call, and the only kinds of objects you could
create, were the ones that Ruby defined for you. Now, it’s your turn. You’re going to learn
to create your own methods. You’ll also create your own classes—templates for new
objects. You’ll decide what objects based on your class will be like. You’ll use instance
variables to define what those objects know, and instance methods to define what they
do. And most importantly, you’ll discover how defining your own classes can make your
code easier to read and maintain.
Defining methods 36
Calling methods you’ve defined 37
Objects Method names 38
Parameters 38
Return values 42
Returning from a method early 43
Some messy methods 44
Too many arguments 45
Too many “if ” statements 45
Designing a class 46
What’s the difference between a class and an object? 47
Your first class 48
Creating new instances (objects) 48
Breaking up our giant methods into classes 49
Creating instances of our new animal classes 50
Class Updating our class diagram with instance methods 51
Local variables live until the method ends 55
Instance variables live as long as the instance does 56
Encapsulation 58
Attribute accessor methods 59
Using accessor methods 61
Attribute writers and readers 62
Ensuring data is valid with accessors 69
Errors—the “emergency stop” button 70
Using “raise” in our attribute writer methods 71
Your Ruby Toolbox 73
vii
table of contents
inheritance
3
Relying on Your Parents
So much repetition!Your new classes representing the different types of
vehicles and animals are awesome, it’s true. But you’re having to copy instance
methods from class to class. And the copies are starting to fall out of sync—some
are fine, while others have bugs. Weren’t classes supposed to make code easier to
maintain?
In this chapter, we’ll learn how to use inheritance to let your classes share methods.
Fewer copies means fewer maintenance headaches!
viii
table of contents
initializing instances
4
Off to a Great Start
Right now, your class is a time bomb. E
very instance you create
starts out as a clean slate. If you call certain instance methods before adding data,
an error will be raised that will bring your whole program to a screeching halt.
In this chapter, we’re going to show you a couple of ways to create objects that are
safe to use right away. We’ll start with the initialize method, which lets you
pass in a bunch of arguments to set up an object’s data at the time you create it.
Then we’ll show you how to write class methods, which you can use to create and
set up an object even more easily.
ix
table of contents
5
Better Than Loops
A whole lot of programming deals with lists of things.Lists of
addresses. Lists of phone numbers. Lists of products. Matz, the creator of Ruby, knew
this. So he worked really hard to make sure that working with lists in Ruby is really easy.
First, he ensured that arrays, which keep track of lists in Ruby, have lots of powerful
methods to do almost anything you might need with a list. Second, he realized that writing
code to loop over a list to do something with each item, although tedious, is something
developers were doing a lot. So he added blocks to the language, and removed the need
for all that looping code. What is a block, exactly? Read on to find out…
Arrays 156
Accessing arrays 157
Arrays are objects, too! 158
Looping over the items in an array 161
The repeating loop 162
Eliminating repetition…the WRONG way… 165
Blocks 167
Defining a method that takes blocks 168
Your first block 169
Flow of control between a method and block 170
Calling the same method with different blocks 171
Calling a block multiple times 172
Block parameters 173
Using the “yield” keyword 174
Block formats 175
The “each” method 179
DRYing up our code with “each” and blocks 181
Blocks and variable scope 184
Our complete invoicing methods 188
We’ve gotten rid of the repetitive loop code! 188
Utilities and appliances, blocks and methods 191
Your Ruby Toolbox 192
6
How Should I Handle This?
You’ve seen only a fraction of the power of blocks.Up until now,
the methods have just been handing data off to a block, and expecting the block to
handle everything. But a block can also return data to the method. This feature lets
the method get directions from the block, allowing it to do more of the work.
In this chapter, we’ll show you some methods that will let you take a big, complicated
collection, and use block return values to cut it down to size.
xi
table of contents
hashes
7
Labeling Data
Throwing things in piles is fine, until you need to find
something again.You’ve already seen how to create a collection of objects
using an array. You’ve seen how to process each item in an array, and how to find
items you want. In both cases, you start at the beginning of the array, and look
through Every. Single. Object. You’ve also seen methods that take big collections
of parameters. You’ve seen the problems this causes: method calls require a big,
confusing collection of arguments that you have to remember the exact order for.
What if there were a kind of collection where all the data had labels on it? You could
quickly find the elements you needed! In this chapter, we’ll learn about Ruby hashes,
which do just that.
xii
table of contents
references
8
Crossed Signals
Ever sent an email to the wrong contact?You probably had a
hard time sorting out the confusion that ensued. Well, Ruby objects are just like
those contacts in your address book, and calling methods on them is like sending
messages to them. If your address book gets mixed up, it’s possible to send
messages to the wrong object. This chapter will help you recognize the signs that
this is happening, and help you get your programs running smoothly again.
Some confusing bugs 258
The heap 259
References 260
When references go wrong 261
Aliasing 262
Fixing the astronomer’s program 264
Quickly identifying objects with “inspect” 266
Problems with a hash default object 267
We’re actually modifying the hash default object! 269
A more detailed look at hash default objects 270
Back to the hash of planets and moons 271
Our wish list for hash defaults 272
Hash default blocks 273
The astronomer’s hash: Our final code 279
Using hash default objects safely 280
Hash default object rule #1: Don’t modify the default object 281
Hash default object rule #2: Assign values to the hash 282
The rule of thumb for hash defaults 283
Your Ruby Toolbox 284
Betty Bell
Betty Bell 2106 W Oak St Candace Camden
2106 W Oak St Candace Camden Heap, RB 90210 2106 W Oak St
Heap, RB 90210 2110 W Oak St Heap, RB 90210
Heap, RB 90210
xiii
table of contents
mixins
9
Mix It Up
Inheritance has its limitations.You can only inherit methods from one
class. But what if you need to share several sets of behavior across several classes?
Like methods for starting a battery charge cycle and reporting its charge level—you
might need those methods on phones, power drills, and electric cars. Are you going
to create a single superclass for all of those? (It won’t end well if you try.) Or methods
for starting and stopping a motor. Sure, the drill and the car might need those, but the
phone won’t!
In this chapter, we’ll learn about modules and mixins, a powerful way to group
methods together and then share them only with particular classes that need them.
xiv
table of contents
10
Ready-Made Mixes
You’ve seen that mixins can be useful. But you haven’t seen their
full power yet. The Ruby core library includes two mixins that will blow your mind.
The first, Comparable, is used for comparing objects. You’ve used operators
like <, >, and == on numbers and strings, but Comparable will let you use
them on your classes. The second mixin, Enumerable, is used for working
with collections. Remember those super-useful find_all, reject, and map
methods that you used on arrays before? Those came from Enumerable. But
that’s a tiny fraction of what Enumerable can do. And again, you can mix it into
your classes. Read on to see how!
I’ll take
this one!
Mixins built into Ruby 312
A preview of the Comparable mixin 313
Choice (of) beef 314
Prime
Implementing a greater-than method on the Steak class 315
Choice
Select Constants 316
We have a lot more methods to define… 317
The Comparable mixin 318
The spaceship operator 319
Implementing the spaceship operator on Steak 320
Mixing Comparable into Steak 321
How the Comparable methods work 322
Our next mixin 325
The Enumerable module 326
A class to mix Enumerable into 327
Mixing Enumerable into our class 328
Inside the Enumerable module 329
Your Ruby Toolbox 332
xv
table of contents
documentation
11
Read the Manual
There isn’t enough room in this book to teach you all of Ruby.
There’s an old saying: “Give someone a fish, and you feed them for a day. Teach them
how to fish, and you feed them for a lifetime.” We’ve been giving you fish so far. We’ve
shown you how to use a few of Ruby’s classes and modules. But there are dozens
more, some of them applicable to your problems, that we don’t have room to cover.
So it’s time to teach you how to fish. There’s excellent documentation freely available
on all of Ruby’s classes, modules, and methods. You just have to know where to find it,
and how to interpret it. That’s what this chapter will show you.
xvi
table of contents
exceptions
12
Handling the Unexpected
In the real world, the unexpected happens.Someone could
delete the file your program is trying to load, or the server your program is trying to
contact could go down. Your code could check for these exceptional situations, but
those checks would be mixed in with the code that handles normal operation. (And
that would be a big, unreadable mess.)
This chapter will teach you all about Ruby’s exception handling, which lets you write
code to handle the unexpected, and keep it separate from your regular code.
Ouch...
Our code so far… 373
nt
im
Whew! Thanks!
rr
or
xvii
table of contents
unit testing
13
Code Quality Assurance
Are you sure your software is working right now? Really sure?
Before you sent that new version to your users, you presumably tried out the new
features to ensure they all worked. But did you try the old features to ensure you didn’t
break any of them? All the old features? If that question makes you worry, your program
needs automated testing. Automated tests ensure your program’s components work
correctly, even after you change your code.
Unit tests are the most common, most important type of automated test. And Ruby
includes MiniTest, a library devoted to unit testing. This chapter will teach you
everything you need to know about it!
ListWithCommas Automated tests find your bugs before someone else does 390
items
A program we should have had automated tests for 391
join
Types of automated tests 393
MiniTest: Ruby’s standard unit-testing library 394
Running a test 395
Testing a class 396
A closer look at the test code 398
Red, green, refactor 400
Tests for ListWithCommas 401
Getting the test to pass 404
Another bug to fix 406
Test failure messages 407
A better way to assert that two values are equal 408
Some other assertion methods 410
Removing duplicated code from your tests 413
The “setup” method 414
The “teardown” method 415
Updating our code to use the “setup” method 416
Your Ruby Toolbox 419
Pass.
P If items is set to ['apple', 'orange', 'pear'], then
join should return "apple, orange, and pear".
Fail!
O If items is set to ['apple', 'orange'],
then join should return "apple and orange".
xviii
table of contents
web apps
14
Serving HTML
This is the 21st century. Users want web apps.Ruby’s got you
covered there, too! Libraries are available to help you host your own web applications
and make them accessible from any web browser. So we’re going to spend these final
two chapters of the book showing you how to build a full web app.
To get started, you’re going to need Sinatra, a third-party library for writing web
applications. But don’t worry, we’ll show you how to use the RubyGems tool (included
with Ruby) to download and install libraries automatically! Then we’ll show you just
enough HTML to create your own web pages. And of course, we’ll show you how to
serve those pages to a browser!
Writing web apps in Ruby 422
Our task list 423
Project directory structure 424
Browsers, requests, servers, and responses 425
Downloading and installing libraries with RubyGems 426
Installing the Sinatra gem 427
A simple Sinatra app 428
Request type 430
Resource path 431
Sinatra routes 432
Making a movie list in HTML 435
Accessing the HTML from Sinatra 436
A class to hold our movie data 438
Setting up a Movie object in the Sinatra app 439
ERB embedding tags 440
Looping over several movie titles in our HTML 446
Letting users add data with HTML forms 449
Getting an HTML form for adding a movie 450
HTML tables 451
Cleaning up our form with an HTML table 452
Your Ruby Toolbox 454
xix
table of contents
15
Keep It Around
Your web app is just throwing users’ data away.You’ve set up a
form for users to enter data into. They’re expecting that you’ll save it, so that it can be
retrieved and displayed to others later. But that’s not happening right now! Anything
they submit just disappears.
In this, our final chapter, we’ll prepare your app to save user submissions. We’ll show
movies you how to set it up to accept form data. We’ll show you how to convert that data to
Ruby objects, how to save those objects to a file, and how to retrieve the right object
app.rb
again when a user wants to see it. Are you ready? Let’s finish this app!
movies.yml
Saving and retrieving form data 456
Setting the HTML form to send a POST request 460
lib
Setting up a Sinatra route for a POST request 461
movie.rb Converting objects to and from strings with YAML 465
Saving objects to a file with YAML::Store 466
movie_store.rb Saving movies to a file with YAML::Store 467
Finding the next available movie ID 473
views Using our MovieStore class in the Sinatra app 476
Testing the MovieStore 477
index.erb Loading all movies from the MovieStore 478
Loading all movies in the Sinatra app 480
new.erb
Building HTML links to individual movies 481
Named parameters in Sinatra routes 484
show.erb
Using a named parameter to get a movie’s ID 485
Defining routes in order of priority 486
Finding a Movie in the YAML::Store 489
An ERB template for an individual movie 490
Finishing the Sinatra route for individual movies 491
Your Ruby Toolbox 497
xx
table of contents
leftovers
i
The Top Ten Topics (We Didn’t Cover)
We’ve covered a lot of ground, and you’re almost finished
with this book.We’ll miss you, but before we let you go, we wouldn’t feel right
about sending you out into the world without a little more preparation. We can’t possibly
fit everything you’ll need to know about Ruby into these few pages… (Actually, we
did include everything originally, by reducing the type point size to .00004. It all fit, but
nobody could read it. So we threw most of it away.) But we’ve kept all the best bits for
this Top Ten appendix.
This really is the end of the book. Except for the index, of course. (A must-read!)
sales.csv
xxi
the intro
ning question:
In this section, we answer thein bur
book on Ruby?”
“So why DID they put that a
Natürlich geht es auch hier nicht ohne Vorrede ab, ich meine, ohne
ein literarisches Vorwort, – hol’s der Kuckuck!“ begann Iwan
lachend, „und schließlich, was bin ich denn für ein Dichter! ... Also –
die Handlung spielt bei mir im sechzehnten Jahrhundert, damals
aber – dir muß das übrigens schon aus der Schule bekannt sein –,
damals war es allgemein gebräuchlich, die himmlischen Mächte in
poetischen Darstellungen auf die Erde zu bringen. Von Dante will ich
nicht weiter reden. In Frankreich waren es die Schreiber der
Gerichtshöfe, die Passionsbrüderschaften und in den Klöstern die
Mönche, die ganze Vorstellungen gaben, in denen auf der Szene die
Madonna, Engel, Heilige, Christus und selbst Gott dargestellt
wurden. Damals war das alles naiv gemeint. In Victor Hugos Notre
Dame de Paris wird unter Ludwig XI., zur Feier der Geburt des
Dauphins, in Paris, im Saale des Hotel de Ville, unentgeltlich dem
Volke eine erbauliche Vorstellung gegeben, unter dem Titel: ‚Le bon
jugement de la très sainte et gracieuse Vierge Marie‘, in der sie
persönlich erscheint und ihr bon jugement verkündet. Auch bei uns
in Moskau wurden früher, vor Peter, eben solche dramatische
Aufführungen veranstaltet, vornehmlich nach Stoffen aus dem Alten
Testament. Und so gab es denn auch damals, als diese dramatischen
Aufführungen so beliebt waren, überall solche Geschichten,
sogenannte ‚Poeme‘ und ‚Gedichte‘, in denen je nach Bedarf Heilige,
Engel und womöglich alle himmlischen Mächte mitwirkten. In
unseren Klöstern wurden diese Werke vielfach übersetzt und
abgeschrieben, oder man verfaßte ganz neue – und weißt du auch,
wann bereits? Zur Zeit des Tatarenjochs![17] Es gibt zum Beispiel ein
Klosterpoem – natürlich aus dem Griechischen: ‚Der Gang der Mutter
Gottes durch die Hölle‘, von einer Kühnheit der Phantasie, die der
danteschen wirklich nicht nachsteht. Die Mutter Gottes steigt hinab
in die Hölle, und der Erzengel Michael führt sie ‚durch die Qualen‘.
Sie sieht jeden Sünder in seiner Pein. Unter anderem gibt es dort
auch eine äußerst bemerkenswerte Kategorie von Sündern in einem
brennenden See: diejenigen, welche in diesem See bereits so weit
versunken sind, daß sie nicht mehr herausschwimmen können, von
denen heißt es, daß ‚Gott sie bereits vergäße‘ – es ist ein Ausdruck
von ungewöhnlicher Tiefe und Kraft. Und siehe, die erschütterte
Mutter Gottes fällt weinend vor dem Throne des Höchsten nieder
und bittet ihn um Vergebung für alle, die sie dort in der Hölle
gesehen hat, für alle ohne Ausnahme. Ihr Gespräch mit Gott ist
ungemein interessant. Sie fleht; sie hört nicht auf zu flehen; und wie
Gott auf die durchbohrten Hände und Füße ihres Sohnes weist und
sie fragt: ‚Wie soll ich seinen Peinigern vergeben?‘ – da befiehlt sie
allen Heiligen, allen Märtyrern, allen Engeln und Erzengeln mit ihr
zusammen niederzuknien und um die Begnadigung aller ohne
Ausnahme zu flehen. Es endet damit, daß sie von Gott die
Einstellung der Qualen in jedem Jahr vom Karfreitag bis zum
Pfingstsonntag erbittet, und da ertönt aus der Hölle der Dank und
der Lobgesang der Sünder, die laut zu ihm rufen: ‚Gerecht bist du, o
Herr, da du also gerichtet hast.‘ Von der Art wäre nun auch mein
Poem gewesen, wenn ich es in jener Zeit verfaßt hätte. Bei mir
erscheint auf der Szene Er. Allerdings spricht Er kein Wort, Er
erscheint nur und geht vorüber. Fünfzehn Jahrhunderte sind seit
Seinem ersten Erscheinen vergangen, seit der Zeit, da Er den
Menschen versprach, wiederzukommen und sein Reich auf Erden zu
errichten, fünfzehn Jahrhunderte seit der Zeit, da Er, wie sein Jünger
uns berichtet, zu uns sagte, als Er noch unter ihnen wandelte:
‚Wahrlich, ich komme bald. Von jenem Tage aber und der Stunde
weiß nicht einmal der Sohn, nur mein himmlischer Vater weiß es.‘
Doch die Menschheit erwartet Ihn in demselben Glauben und mit
derselben Sehnsucht wie früher. Was sage ich! – in noch größerem
Glauben erwartet sie Ihn, denn fünfzehn Jahrhunderte sind schon
seit der Zeit vergangen, da der Himmel dem Menschen ein
Unterpfand gab ...
‚Was das Herz dir saget, daran glaube:
Der Himmel gibt kein Unterpfand den Menschen.‘
Was natürlich auch so war, das sage ich dir von mir aus. Und siehe,
Er will in seiner Barmherzigkeit wenigstens auf einen Augenblick zum
Volke hinabsteigen, zu dem sich quälenden, dem leidenden,
schmutzig-sündigen, doch kindlich Ihn liebenden Volke. Die
Handlung spielt bei mir in Spanien, in Sevilla, zur Zeit der
schrecklichsten Inquisition, als zum Ruhme Gottes täglich
Scheiterhaufen auf zum Himmel flammten, und endlos, bei
flackerndem Fackelschein,