/
wpgtr.tex
executable file
·10926 lines (7945 loc) · 370 KB
/
wpgtr.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[10pt,twoside]{report}
\usepackage{charter,titlesec,fancyhdr,wrapfig,framed}
\usepackage[pdftex]{graphicx}
\usepackage{colortbl}
\definecolor{white}{gray}{1.0}
\definecolor{gray-5}{gray}{0.95}
\definecolor{gray-10}{gray}{0.9}
\definecolor{gray-20}{gray}{0.8}
\definecolor{gray-30}{gray}{0.7}
\definecolor{gray-40}{gray}{0.6}
\definecolor{fadered}{rgb}{0.8824, 0.9529, 0.8745}
\definecolor{basiccolor}{rgb}{0.0, 0.0, 0.0}
\definecolor{commentcolor}{rgb}{0.2, 0.6, 0.3}
\definecolor{keywordscolor}{rgb}{0.8, 0.1, 0.1}
\definecolor{stringcolor}{rgb}{0.1, 0.3, 0.3}
\definecolor{ricolor}{rgb}{0.5, 0.3, 0.2}
\definecolor{parensaroundricolor}{rgb}{1.0, 0.5, 0.5}
\definecolor{belgradeoperatorcolor}{rgb}{0.2, 0.0, 0.0}
\usepackage{subfigure}
\usepackage[papersize={7.2in,8.8in},bindingoffset=1cm,left=2cm,right=2cm,top=3cm,bottom=2cm]{geometry}
\geometry{twoside}
\usepackage{setspace}
\usepackage[charter]{mathdesign}
\usepackage[small]{caption}
\usepackage[scaled]{beramono}
\usepackage{abstract}
\usepackage{nextpage}
\usepackage{picins}
\usepackage[normalem]{ulem}
\usepackage{manfnt}
\renewcommand{\appendixname}{Expansion Pak No.}
\usepackage{listings}
%\lstset{numbers=left, numberstyle=\scriptsize\ttfamily,
%numbersep=10pt, captionpos=b}
\lstloadlanguages{Ruby}
%[basicstyle=\ttfamily\color{basiccolor},
% commentstyle = \ttfamily\color{commentcolor},
% keywordstyle=\ttfamily\color{keywordscolor},
% stringstyle=\color{stringcolor},
% language=Ruby,
% basicstyle=\small\ttfamily,
% showstringspaces=false,
% ]
\lstset{backgroundcolor=\color{white}}
\lstset{basicstyle=\small\ttfamily}
\lstset{framesep=4pt}
\lstset{language={}}
\newcommand{\inlineCode}{\lstinline[basicstyle=\normalsize\ttfamily]}
\usepackage[colorlinks=true,linkcolor=black,citecolor=black,urlcolor=black,filecolor=black,bookmarks=true]{hyperref}
\hypersetup{
pdfauthor = {why the lucky stiff},
pdftitle = {Why's (Poignant) Guide to Ruby},
pdfsubject = {},
pdfkeywords = {},
pdfcreator = {LaTeX},
pdfproducer = {pdflatex}}
%\include{styles/draft}
\include{styles/chapterleft}
\include{styles/misc}
\setlength{\parskip}{2mm}
\setlength{\parindent}{0mm}
\renewcommand{\baselinestretch}{1.2}
\renewcommand{\arraystretch}{1.2}
\renewcommand{\headrulewidth}{0.25pt}
\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{#1}}
%\setlength{\marginparwidth}{1.5cm}
%\newcommand{\note}[1]{\marginpar{\color{gray-40}\footnotesize \flushleft #1}}
\newcommand{\note}[1]{}
\newcommand{\imageCourtesy}[2]{Image courtesy of #1 \cite{#2}.}
\fancyhf{}
\fancyhead[EL,OR]{\thepage}
\fancyhead[ER]{\leftmark}
\fancyhead[OL]{\rightmark}
\fancypagestyle{plain} {
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
}
\lstnewenvironment{todo}{\lstset{numbers=none,frame=none,backgroundcolor=\color{fadered}}}{}
\begin{document}
\pagestyle{empty}
\begin{titlepage}
\begin{center}
\vspace*{2cm}
\normalfont\noindent\bf\Huge{Why's (Poignant) Guide to Ruby}
\vfill
\normalfont\noindent\large{tenderly written and illustrated by}
\vspace*{-0.2cm}
\normalfont\noindent\large{\em why the lucky stiff}
\end{center}
\end{titlepage}
\newpage
\thispagestyle{empty}
\mbox{}
\newpage
\pagestyle{empty}
\begin{center}
\vspace*{4cm}
This PDF edition of \_why's Poignant Guide to Ruby is distributed
under the Creative Commons Attribution-ShareAlike 3.0 Unported
(CC BY-SA 3.0)
\vfill
http://creativecommons.org/licenses/by-sa/3.0/\\\\
Credits go to why the lucky stiff for writing and illustrating the
book.\\
The initial LaTeX version was created by Michael Specht. Further
improvements and minimal actualization by Alexandre Gravier.
\hspace{8.5cm}--- A
\vspace{5cm}
\end{center}
\newpage
\thispagestyle{empty}
\mbox{}
\cleartoevenpage
\setcounter{page}{2}
\setcounter{tocdepth}{1}
\setcounter{secnumdepth}{2}
\begin{spacing}{1.135}
\tableofcontents
\end{spacing}
\newpage
\thispagestyle{empty}
%\cleardoublepage
\pagestyle{fancy}
\fancypagestyle{plain} {
\renewcommand{\headrulewidth}{0.25pt}
\fancyhf{}
\fancyhead[EL,OR]{\thepage}
}
\cleartooddpage
\chapter{About this Book}
\vfill
\begin{center}
\includegraphics{cache/chapterpoignantguide1.png}
\end{center}
\vspace{2cm}
\newpage
\thispagestyle{empty}
\mbox{}
\clearpage
\includegraphics[width=1.0\textwidth]{cache/1.png}
\includegraphics[width=1.0\textwidth]{cache/2.png}
\includegraphics[width=1.0\textwidth]{cache/3.png}
\includegraphics[width=1.0\textwidth]{cache/4.png}
\newpage
\thispagestyle{empty}
\mbox{}
\cleartooddpage
\chapter{Kon'nichi wa, Ruby}
\vfill
\begin{center}
\includegraphics{cache/chapterpoignantguide2.png}
\end{center}
\vspace{2cm}
\newpage
\thispagestyle{empty}
\mbox{}
\clearpage
\section{Opening This Book}
Pretend that you've opened this book (although you probably {\em have}
opened this book), just to find a huge onion right in the middle
crease of the book. (The manufacturer of the book has included the
onion at my request.)
So you're like, ``Wow, this book comes with an onion!'' (Even if you
don't particularly like onions, I'm sure you can appreciate the
logistics of shipping any sort of produce discreetly inside of an
alleged programming manual.)
Then you ask yourself, ``Wait a minute. I thought this was a book on
Ruby, the incredible new programming language from Japan. And
although I can appreciate the logistics of shipping any sort of
produce discreetly inside of an alleged programming manual: Why an
onion? What am I supposed to do with it?''
No. Please don't puzzle over it. You don't need to do anything with
the onion. Set the onion aside and let {\em it} do something with
{\em you}.
I'll be straight with you. I want you to cry. To weep. To whimper
sweetly. This book is a {\bf poignant} guide to Ruby. That means
code so beautiful that tears are shed. That means gallant tales and
somber truths that have you waking up the next morning in the arms of
this book. Hugging it tightly to you all the day long. If necessary,
fashion a makeshift hip holster for {\em Why's (Poignant) Guide to
Ruby}, so you can always have this book's tender companionship.
You really must sob once. Or at least sniffle. And if not, then the
onion will make it all happen for you.
\section{The Dog Story}
So try this first bit of poignancy on for size:
One day I was walking down one of those busy roads covered with car
dealerships (this was shortly after my wedding was called off) and I
found an orphaned dog on the road. A wooly, black dog with greenish
red eyes. I was kind of feeling like an orphan myself, so I took a
couple balloons that were tied to a pole at the dealership and I
relocated them to the dog's collar. Then, I decided he would be my
dog. I named him Bigelow.
We set off to get some Milkbones for Bigelow and, afterwards, head
over to my place, where we could sit in recliners and listen to
Gorky's Zygotic Mynci. Oh, and we'd also need to stop by a thrift
store and get Bigelow his own recliner.
But Bigelow hadn't accepted me as his master. So five minutes later,
the stupid dog took a different crosswalk than I did and I never
caught up. So whereas he had previously only been lost once, he was
now lost twice. I slowed my pace towards the life of Milkbones and an
extra recliner. I had a dog for five minutes.
Stupid Benedict Arnold of a dog. I sat on a city bench and threw
pinecones at a statue of three sheep crossing a bridge. After that, I
wept for hours. The tears just came. Now there's a little something
poignant to get you started.
I wonder where he went with all those balloons. That crazy dog must
have looked like a party with legs.
It wasn't much later that I pulled my own Bigelow. I printed out a
bunch of pages on Ruby. Articles found around the Web. I scanned
through them on a train ride home one day. I flipped through them for
five minutes and then gave up. Not impressed.
I sat, staring out the window at the world, a life-sized blender
mixing graffiti and iron smelts before my eyes. {\em This world's too
big for such a a little language}, I thought. {\em Poor little thing
doesn't stand a chance. Doesn't have legs to stand on. Doesn't
have arms to swim.}
And yet, there I was. One little man on a flimsy little train (and I
even still had a baby tooth to lose at the time) out of billions of
people living on a floating blue rock. How can I knock Ruby? Who's
to say that I'm not going to happen to choke on my cell phone and die
later that evening. Why's dead, Ruby lives on.
The gravestone:
\begin{quote}
What's in his trachea?\end{quote}
Oh, look, a Nokia!
Just my luck. Finally get to have a good, long sleep underground,
only to be constantly disturbed by {\em Pachelbel's Canon} going off
in my stomach.
\section{The Red Sun Rises}
So, now you're wondering why I changed my mind about Ruby. The quick
answer is: we clicked.
Like when you meet Somebody in college and they look like somebody who
used to hit you in the face with paintbrushes when you were a kid.
And so, impulsively, you conclude that this new Somebody is likely a
non-friend. You wince at their hair. You hang up phones loudly
during crucial moments in their anecdotes. You use your pogo stick
right there where they are trying to walk!
Six months later, somehow, you and Somebody are sitting at a fountain
having a perfectly good chat. Their face doesn't look so much like
that childhood nemesis. You've met the Good Twin. You clicked.
So whereas I should probably be pounding your teeth in with hype about
Ruby and the tightly-knit cadre of pertinent ancronyms that accompany
it everywhere (whetting the collective whistles of your bosses and
their bosses' bosses), instead I will just let you coast. I'll let
you freefall through some code, interjecting occassionally with my own
heartfelt experiences. It'll be quite easy, quite natural.
I should offer you some sort of motivation, though. So, Smotchkkiss,
I'm going to give my three best reasons to learn Ruby and be done with
it.
\begin{enumerate}
\item {\bf Brain health.}
Vitamin R. Goes straight to the head. Ruby will teach you to {\em
express} your ideas through a computer. You will be writing stories
for a machine.
Creative skills, people. Deduction. Reason. Nodding
intelligently. The language will become a tool for you to better
connect your mind to the world. I've noticed that many experienced
users of Ruby seem to be clear thinkers and objective. (In contrast
to: heavily biased and coarse.)
\item {\bf One man on one island.}
Ruby was born in Japan. Which is freaky. Japan is not known for its
software. And since programming languages are largely written in
English, who would suspect a language to come from Japan?
And yet, here we have Ruby. Against the odds, Yukihiro Matsumoto
created Ruby on February 24, 1993. For the past ten years, he has
steadily brought Ruby to a global audience. It's triumphant and noble
and all that. Support diversity. Help us tilt the earth just a bit.
\item {\bf Free.}
Using Ruby costs nothing. The code to Ruby itself is open for all of
the world to inhale/exhale. Heck, this book is free. It's all part
of a great, big giveaway that should have some big hitch to it.
You'd think we'd make you buy vacuums or timeshare or fake
Monets. You'd think there'd be a 90 minute presentation where the
owner of the company comes out at the end and knuckles you into
sealing the deal.
Nope, free.
\end{enumerate}
With that, it's time for the book to begin. You can now get out your
highlighter and start dragging it along each captivating word from
this sentence on. I think I have enough hairspray and funny money on
my person to keep me sustained until the final page.
\section{How Books Start}
Now, if you ever have read a book, you know that no book can properly
start without an exorbitant amount of synergy. Yes, synergy. Maybe
you didn't know this. Synergy means that you and I are supposed to
cooperate to make this a great reading experience.
We start off the book by getting along well in the Introduction. This
togetherness, this {\bf synergy}, propels us through the book, with me
guiding you on your way. You give me a reassuring nod or snicker to
indicate your progress.
I'm Peter Pan holding your hand. Come on, Wendy! Second star to the
right and on till morning.
One problem here. I don't get along well with people. I don't hold
hands very well.
Any of my staff will tell you. At the Opening Ceremonies of This Book
(a catered event with stadium seating), I discovered that the cucumber
sandwiches weren't served in tea towels. As a result, the butter
hadn't set with the cucumbers right... Anyways, I made a big scene and
set fire to some of the advertising trucks outside. I smashed this
spotlight to pieces and so on. I had this loud maniacal laughing
thing going on deep into that night. It was a real mess.
But, since I don't get along well with people, I hadn't invited anyone
but myself to the Opening Ceremonies of This Book. So it wasn't
really that embarassing. I kept it under wraps and no one found out
about the whole ordeal.
So you've got to know that {\bf synergy} doesn't actually mean {\bf
synergy} in this book. I can't do normal {\bf synergy}. No, in this
book, {\bf synergy} means {\bf cartoon foxes}. What I'm saying is:
this book will be starting off with an exorbitant amount of {\bf
cartoon foxes}.
And I will be counting on you to turn them into {\bf synergy}.
\newpage
\thispagestyle{empty}
\mbox{}
\cleartooddpage
\chapter{A Quick (and Hopefully Painless) Ride Through Ruby \mbox{(with Cartoon Foxes)}}
\vfill
\begin{center}
\includegraphics{cache/chapterpoignantguide3.png}
\end{center}
\vspace{2cm}
\newpage
\thispagestyle{empty}
\mbox{}
\clearpage
\includegraphics[width=1.0\textwidth]{cache/5.png}
Yeah, these are the two. My asthma's kickin in so I've got to go take
a puff of medicated air just now. Be with you in a moment.
\includegraphics[width=1.0\textwidth]{cache/6.png}
I'm told that this chapter is best accompanied by a rag. Something
you can mop your face with as the sweat pours off your face.
Indeed, we'll be racing through the whole language. Like striking
every match in a box as quickly as can be done.
\section{Language and I MEAN Language}
\includegraphics[width=1.0\textwidth]{cache/7.png}
My conscience won't let me call Ruby a {\em computer} language. That
would imply that the language works primarily on the computer's terms.
That the language is designed to accomodate the computer, first and
foremost. That therefore, we, the coders, are foreigners, seeking
citizenship in the computer's locale. It's the computer's language
and we are translators for the world.
But what do you call the language when your brain begins to think in
that language? When you start to use the language's own words and
colloquialisms to express yourself. Say, the computer can't do that.
How can it be the computer's language? It is ours, we speak it
natively!
We can no longer truthfully call it a {\em computer} language. It is
{\em coderspeak}. It is the language of our thoughts.
{\bf Read the following aloud to yourself.}
\begin{quote}
\lstinline[breaklines=true]|5.times { print "Odelay!" }|\end{quote}
In English sentences, punctuation (such as periods, exclamations,
parentheses) are silent. Punctuation adds meaning to words, helps
give cues as to what the author intended by a sentence. So let's read
the above as: {\em Five times print ``Odelay!''.}
Which is exactly what this small Ruby program does. Beck's mutated
Spanish exclamation will print five times on the computer screen.
\newpage
{\bf Read the following aloud to yourself.}
\begin{quote}
\lstinline[breaklines=true]|exit unless "restaurant".include? "aura"|\end{quote}
Here we're doing a basic reality check. Our program will {\bf exit}
(the program will end) {\bf unless} the word {\bf restaurant} contains
(or {\bf includes}) the word {\bf aura}. Again, in English: {\em Exit
unless the word restaurant includes the word aura.}
Ever seen a programming language use question marks so effectively?
Ruby uses some punctuation, such as exclamations and question marks,
to enhance readability of the code. We're asking a question in the
above code, so why not make that apparent?
{\bf Read the following aloud to yourself.}
\begin{quote}
\lstinline[breaklines=true]$['toast', 'cheese', 'wine'].each { |food| print food.capitalize }$\end{quote}
While this bit of code is less readable and sentence-like than the
previous examples, I'd still encourage you to read it aloud. While
Ruby may sometimes read like English, it sometimes reads as a shorter
English. Fully translated into English, you might read the above as:
{\em With the words `toast', `cheese', and `wine': take each food and
print it capitalized.}
The computer then courteously responds:
\lstinline[breaklines=true]|Toast|,
\lstinline[breaklines=true]|Cheese| and
\lstinline[breaklines=true]|Wine|.
At this point, you're probably wondering how these words actually fit
together. Smotchkkiss is wondering what the dots and brackets mean.
I'm going to discuss the various {\em parts of speech} next.
All you need to know thus far is that Ruby is basically built from
sentences. They aren't exactly English sentences. They are short
collections of words and punctuation which encompass a single thought.
These sentences can form books. They can form pages. They can form
entire novels, when strung together. Novels that can be read by
humans, but also by computers.
\section{The Parts of Speech}
Just like the white stripe down a skunk's back and the winding, white
train of a bride, many of Ruby's parts of speech have visual cues to
help you identify them. Punctuation and capitalization will help your
brain to see bits of code and feel intense recognition. Your mind will
frequently yell {\em Hey, I know that guy!} You'll also be able to
name-drop in conversations with other Rubyists.
Try to focus on the look of each of these parts of speech. The rest
of the book will detail the specifics. I give short descriptions for
each part of speech, but you don't have to understand the explanation.
By the end of this chapter, you should be able to recognize every part
of a Ruby program.
\subsection{Variables}
Any plain, lowercase word is a variable in ruby. Variables may
consist of letters, digits and underscores.
\begin{quote}
\lstinline[breaklines=true]|x|, \lstinline[breaklines=true]|y|,
\lstinline[breaklines=true]|banana2| or
\lstinline[breaklines=true]|phone_a_quail| are examples.\end{quote}
Variables are like nicknames. Remember when everyone used to call you
Stinky Pete? People would say, ``Get over here, Stinky Pete!'' And
everyone miraculously knew that Stinky Pete was you.
With variables, you give a nickname to something you use frequently.
For instance, let's say you run an orphanage. It's a mean orphanage.
And whenever Daddy Warbucks comes to buy more kids, we insist that he
pay us {\bf one-hundred twenty-one dollars and eight cents} for the
kid's teddy bear, which the kid has become attached to over in the
darker moments of living in such nightmarish custody.
\begin{quote}
\lstinline[breaklines=true]|teddy_bear_fee = 121.08|\end{quote}
Later, when you ring him up at the cash register (a really souped-up
cash register which runs Ruby!), you'll need to add together all his
charges into a {\bf total}.
\begin{quote}
\lstinline[breaklines=true]|total = orphan_fee + teddy_bear_fee + gratuity|\end{quote}
Those variable nicknames sure help. And in the seedy underground of
child sales, any help is appreciated I'm sure.
\includegraphics[width=0.3575\textwidth]{cache/8.png}
\subsection{Numbers}
The most basic type of number is an {\em integer}, a {\bf series of
digits} which can start with a {\bf plus or minus sign}.
\begin{quote}
\lstinline[breaklines=true]|1|, \lstinline[breaklines=true]|23|, and
\lstinline[breaklines=true]|-10000| are examples.\end{quote}
Commas are not allowed in numbers, but underscores are. So if you
feel the need to mark your thousands so the numbers are more readable,
use an underscore.
\begin{quote}
\lstinline[breaklines=true]|population = 12_000_000_000|\end{quote}
Decimal numbers are called {\em floats} in Ruby. Floats consist of
numbers with {\bf a decimal place} or {\bf scientific notation}.
\begin{quote}
\lstinline[breaklines=true]|3.14|,
\lstinline[breaklines=true]|-808.08| and
\lstinline[breaklines=true]|12.043e-04| are examples.\end{quote}
\subsection{Strings}
Strings are any sort of characters (letters, digits, punctuation)
surrounded by quotes. Both single and double {\bf quotes} are used to
create strings.
\begin{quote}
\lstinline[breaklines=true]|"sealab"|,
\lstinline[breaklines=true]|'2021'|, or
\lstinline[breaklines=true]|"These cartoons are hilarious!"| are
examples.\end{quote}
When you enclose characters in quotes, they are stored together as a
single string.
Think of a reporter who is jotting down the mouthnoises of a rambling
celebrity. ``I'm a lot wiser,'' says Avril Lavigne. ``Now I know
what the business is like -- what you have to do and how to work it.''
\begin{lstlisting}[basicstyle=\ttfamily\color{basiccolor},
commentstyle = \ttfamily\color{commentcolor},
keywordstyle=\ttfamily\color{keywordscolor},
stringstyle=\color{stringcolor},
language=Ruby,
basicstyle=\small\ttfamily,
showstringspaces=false,
]
avril_quote = "I'm a lot wiser. Now I know
what the business is like -- what you have
to do and how to work it."
\end{lstlisting}
So, just as we stored a number in the {\bf teddy\_bear\_fee} variable,
now we're storing a collection of characters (a string) in the {\bf
avril\_quote} variable. The reporter sends this quote to the
printers, who just happen to use Ruby to operate their printing press.
\begin{lstlisting}[basicstyle=\ttfamily\color{basiccolor},
commentstyle = \ttfamily\color{commentcolor},
keywordstyle=\ttfamily\color{keywordscolor},
stringstyle=\color{stringcolor},
language=Ruby,
basicstyle=\small\ttfamily,
showstringspaces=false,
]
print oprah_quote
print avril_quote
print ashlee_simpson_debacle
\end{lstlisting}
\includegraphics[width=0.3575\textwidth]{cache/9.png}
\subsection{Symbols}
Symbols are words that look just like variables. Again, they may
contain letters, digits, or underscores. But they {\bf start with a
colon}.
\begin{quote}
\lstinline[breaklines=true]|:a|, \lstinline[breaklines=true]|:b|, or
\lstinline[breaklines=true]|:ponce_de_leon| are examples.\end{quote}
Symbols are lightweight strings. Usually, symbols are used in
situations where you need a string but you won't be printing it to the
screen.
You could say a symbol is a bit easier on the computer. It's like an
antacid. The colon indicates the bubbles trickling up from your
computer's stomach as it digests the symbol. Ah. Sweet, sweet
relief.
\includegraphics[width=0.3575\textwidth]{cache/10.png}
\subsection{Constants}
Constants are words like variables, but constants are {\bf
capitalized}. If variables are the nouns of Ruby, then think of
constants as the proper nouns.
\begin{quote}
\lstinline[breaklines=true]|Time|, \lstinline[breaklines=true]|Array|
or \lstinline[breaklines=true]|Bunny_Lake_is_Missing| are
examples.\end{quote}
In English, proper nouns are capitalized. The Empire State Building.
You can't just move The Empire State Building. You can't just decide
that the Empire State Building is something else. Proper nouns are
like that. They refer to something very specific and usually don't
change over time.
In the same way, constants can't be changed after they are set.
\begin{quote}
\lstinline[breaklines=true]|EmpireStateBuilding = "350 5th Avenue, NYC, NY"|\end{quote}
If we try to change the constant, Ruby will complain to us. Such
things are frowned upon.
\includegraphics[width=0.3575\textwidth]{cache/11.png}
\subsection{Methods}
If variables and constants are the nouns, then methods are the
verbs. Methods are usually attached to the end of variables and
constants by a {\bf dot}. You've already seen methods at work.
\begin{quote}
\lstinline[breaklines=true]|front_door.open|\end{quote}
In the above, {\bf open} is the method. It is the action, the
verb. In some cases, you'll see actions chained together.
\begin{quote}
\lstinline[breaklines=true]|front_door.open.close|\end{quote}
We've instructed the computer to open the front door and then
immediately close it.
\begin{quote}
\lstinline[breaklines=true]|front_door.is_open?|\end{quote}
The above is an action as well. We're instructing the computer to
test the door to see if it's open. The method could be called
\lstinline[breaklines=true]|Door.test_to_see_if_its_open|, but the
\lstinline[breaklines=true]|is_open?| name is succinct and just as
correct. Both exclamation marks and question marks may be used in
method names.
\subsection{Method arguments}
A method may require more information in order to perform its action.
If we want the computer to paint the door, we should provide a color
as well.
Method arguments are attached to the end of a method. The arguments
are usually surrounded by {\bf parentheses} and separated by {\bf
commas}.
\begin{quote}
\lstinline[breaklines=true]|front_door.paint( 3, :red )|\end{quote}
The above paints the front door 3 coats of red.
Think of it as an inner tube the method is pulling along, containing
its extra instructions. The parentheses form the wet, round edges of
the inner tube. The commas are the feet of each argument, sticking
over the edge. The last argument has its feet tucked under so they
don't show.
Like a boat pulling many inner tubes, methods with arguments can be
chained.
\begin{quote}
\lstinline[breaklines=true]|front_door.paint( 3, :red ).dry( 30 ).close()|\end{quote}
The above paints the front door 3 coats of red, dries for 30 minutes,
and closes the door. Even though the last method has no arguments,
you can still put parentheses if you like. There is no use dragging
an empty inner tube, so the parentheses are normally dropped.
Some methods (such as \lstinline[breaklines=true]|print|) are kernel
methods. These methods are used throughout Ruby. Since they are so
common, you won't use the dot.
\begin{quote}
\lstinline[breaklines=true]|print "See, no dot."|\end{quote}
\subsection{Class methods}
Like the methods described above (also called {\em instance} methods),
class methods are usually attached after variables and constants.
Rather than a dot, a {\bf double colon} is used.
\begin{quote}
\lstinline[breaklines=true]|Door::new( :oak )|\end{quote}
As seen above, the \lstinline[breaklines=true]|new| class method is
most often used to create things. In the above example, we're asking
Ruby to make a new oak door for us. Of course, Ruby has to have an
understanding of how to make a door--as well as a wealth of timber,
lumberjacks, and those long, wiggily, two-man saws.
\includegraphics[width=0.3575\textwidth]{cache/12.png}
\subsection{Global variables}
Variables which begin with a {\bf dollar sign} are global.
\begin{quote}
\lstinline[breaklines=true]|$x|, \lstinline[breaklines=true]|$1|,
\lstinline[breaklines=true]|$chunky| and
\lstinline[breaklines=true]|$CHunKY_bACOn| are examples.\end{quote}
Most variables are rather temporary in nature. Some parts of your
program are like little houses. You walk in and they have their own
variables. In one house, you may have a
\lstinline[breaklines=true]|dad| that represents Archie, a travelling
salesman and skeleton collector. In another house,
\lstinline[breaklines=true]|dad| could represent Peter, a lion tamer
with a great love for flannel. Each house has its own meaning for
\lstinline[breaklines=true]|dad|.
With global variables, you can be guaranteed that the variable is the
same in every little house. The dollar sign is very appropriate.
Every American home respects the value of the dollar. We're crazy for
the stuff. Try knocking on any door in America and hand them cash. I
can guarantee you won't get the same reaction if you knock on a door
and offer Peter, a lion tamer with a great love for flannel.
Global variables can be used anywhere in your program. They never go
out of sight.
\subsection{Instance variables}
Variables which begin with an {\bf at} symbol are instance variables.
\begin{quote}
\lstinline[breaklines=true]|@x|, \lstinline[breaklines=true]|@y|, and
\lstinline[breaklines=true]|@only_the_chunkiest_cut_of_bacon_I_have_ever_seen|
are examples.\end{quote}
These variables are often used to define the attributes of something.
For example, you might provide Ruby with the width of the
\lstinline[breaklines=true]|front_door| by setting the
\lstinline[breaklines=true]|@width| variable inside that
\lstinline[breaklines=true]|front_door|. Instance variables are used
to define characteristics of a single object in Ruby.
Think of the {\bf at} symbol as meaning {\bf attribute}.
\subsection{Class variables}
Variables which begin with {\bf double at} symbols are class
variables.
\begin{quote}
\lstinline[breaklines=true]|@@x|, \lstinline[breaklines=true]|@@y|,
and
\lstinline[breaklines=true]|@@i_will_take_your_chunky_bacon_and_raise_you_two|
are examples.\end{quote}
Class variables, too, are used to define attributes. But rather than
defining an attribute for a single object in Ruby, class variables
give an attribute to many related objects in Ruby. If instance
variables set attributes for a single
\lstinline[breaklines=true]|front_door|, then class variables set
attributes for everything that is a \lstinline[breaklines=true]|Door|.
Think of the {\bf double at} prefix as meaning {\bf attribute all}.
Additionally, you can think of a swarm of {\bf AT-ATs} from {\em Star
Wars}, which are all commanded by Ruby. You change a class variable
and not just one changes, they all change.
\includegraphics[width=0.3575\textwidth]{cache/13.png}
\subsection{Blocks}
Any code surrounded by {\bf curly braces} is a block.
\begin{quote}
\lstinline[breaklines=true]|2.times { print "Yes, I've used chunky bacon in my examples, but never again!" }| is an example.\end{quote}
With blocks, you can group a set of instructions together so that they
can be passed around your program. The curly braces give the
appearance of crab pincers that have snatched the code and are holding
it together. When you see these two pincers, remember that the code
inside has been pressed into a single unit.
It's like one of those little Hello Kitty boxes they sell at the mall
that's stuffed with tiny pencils and microscopic paper, all crammed
into a glittery transparent case that can be concealed in your palm
for covert stationary operations. Except that blocks don't require so
much squinting.
The curly braces can also be traded for the words {\bf do} and {\bf
end}, which is nice if your block is longer than one line.
\begin{lstlisting}[basicstyle=\ttfamily\color{basiccolor},
commentstyle = \ttfamily\color{commentcolor},
keywordstyle=\ttfamily\color{keywordscolor},
stringstyle=\color{stringcolor},
language=Ruby,
basicstyle=\small\ttfamily,
showstringspaces=false,
]
loop do
print "Much better."
print "Ah. More space!"
print "My back was killin' me in those crab pincers."
end
\end{lstlisting}
\subsection{Block arguments}
Block arguments are a set of variables surrounded by {\bf pipe}
characters and separated by {\bf commas}.
\begin{quote}
\lstinline[breaklines=true]$|en||x|$,
\lstinline[breaklines=true]$|x,y|$, and
\lstinline[breaklines=true]$|up, down, all_around|$ are
examples.\end{quote}