4th Edition - SapphireSteel

2y ago
11 Views
2 Downloads
1.48 MB
104 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Adele Mcdaniel
Transcription

BYHUW COLLINGBOURNE4th EditionYOUR FREE GUIDE TO PROGRAMMING RUBYFROM BITWISE COURSESWWW.BITWISECOURSES.COMANDBITWISE BOOKSWWW.BITWISEBOOKS.COM

The Little Book Of Ruby :: www.bitwisebooks.com :: page 2The Little Book Of RubyCopyright 2015 Dark Neon Ltd.All rights reserved.written byHuw CollingbourneDownload source code /The-Little-Book-OfRuby.htmlYou may use this eBook for your own personal use as long as you donot modify the text or remove this copyright notice. You must not make anycharge for this eBook (unless by prior arrangement with the author).First edition: June 2006Second edition: March 2008Third edition: July 2011Fourth edition: July 2015 (minor updates: 4.1, August 2019)NOTE: The 5th Edition of this book is now available as a paperback orKindle eBook.

The Little Book Of Ruby :: www.bitwisebooks.com :: page 3TABLE OF CONTENTSTable of Contents . 3Welcome To The Little Book Of Ruby . 6Learn Ruby In Ten Chapters .6What Is Ruby? .7What Is Rails? .7Installing Ruby .8Ruby 1 or Ruby 2? .8Installing A Ruby Editor or IDE .9SciTE . 9Komodo Edit . 9RubyMine . 9TextMate . 10Get The Source Code Of The Sample Programs .11Running Ruby Programs .11Running Ruby From a Command Prompt .12On Windows. 12On Mac OS X . 12How To Use This Book .14Making Sense Of The Text .14Chapter One . 15Strings and Embedded Evaluation .18Methods .19Numbers .21Testing a Condition: if then.22

The Little Book Of Ruby :: www.bitwisebooks.com :: page 4Chapter Two . 24Instances and Instance Variables .26Constructors – new and initialize .28Inspecting Objects .31Chapter Three . 35Creating a Class Hierarchy .35One Parent, Many Children. .37Superclasses and Subclasses .39Chapter Four . 41Accessor Methods.41Attribute Readers and Writers .43Attributes Create Variables .46Calling Methods of a Superclass .48Class Variables .49Objects ‘share’ Class variables .51Chapter Five . 52Introducing Arrays .52Creating Arrays .53Multi-Dimensional Arrays .56Iterating Over Arrays .57Indexing Into Arrays .59Chapter Six . 62Creating Hashes .62Indexing Into A Hash.65Hash Operations .66Chapter Seven . 68for Loops .68Blocks .72while Loops .73

The Little Book Of Ruby :: www.bitwisebooks.com :: page 5While Modifiers .74Until Loops .76Chapter Eight . 78if.else .79and.or.not.81if.elsif .82? : .83unless .84if and unless Modifiers .84Case Statements .86Chapter Nine. 89A Module Is Like A Class .89Module Methods .90Modules as Namespaces .91Module ‘Instance Methods’ .93Included Modules or ‘Mixins’ .93Including Modules From Files.97Pre-Defined Modules .98Chapter Ten. 99Saving Data .99YAML .99Files .100Moving On.101The Little Book Of Ruby (5th Edition) . 102More Little Programming Books . 103

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 6WELCOME TO THE LITTLE BOOK OF RUBYLearn Ruby In Ten Chapters Chapter One :Chapter Two:Chapter Three:Chapter Four:Strings and MethodsClasses and ObjectsClass HierarchiesAccessors, Attributes, Class VariablesChapter Five:Chapter Six:Chapter Seven:Chapter Eight:Chapter Nine:Chapter Ten:ArraysHashesLoops and IteratorsConditional StatementsModules and MixinsSaving Files, Moving On

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 7What Is Ruby?Ruby is a cross-platform, object-oriented, interpreted language which hasmany features in common with other ‘scripting’ languages such as Perl andPython as well as with ‘pure’ object-oriented languages such as Smalltalk. Itssyntax looks deceptively simple at first sight. In fact, Ruby is a good deal morecomplex than it may appear. The Ruby language was created by YukihiroMatsumoto (commonly known as ‘Matz’) and it was first released in 1995.What Is Rails?Rails is a web development framework (a collection of code libraries andsoftware tools) that uses Ruby as its programming language. It is popularlyknown as ‘Ruby On Rails’. While Rails is an impressive framework, it is notthe be-all and end-all of Ruby. Indeed, if you decide to leap right into Railsdevelopment without first mastering Ruby, you may find that you end upwith an application that you don’t even understand. The Little Book of Ruby isnot about Rails; it concentrates entirely on the Ruby programming language.However, if you intend to program Rails applications, this book will give youthe grounding you need in order to understand Rails code and write your owncustom Ruby On Rails applications.

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 8Installing RubyBefore doing anything else, you need to install Ruby on your computer. If youare using Mac OS X (or some versions of Linux) you may already have Rubyinstalled. At any rate, you can download the latest version of Ruby fromwww.ruby-lang.org. Be sure to download the binaries (not merely the sourcecode). For Windows users, the easiest way to set up Ruby on your system is byusing the Ruby Installer for Windows available from: http://rubyinstaller.org/Ruby 1 or Ruby 2?At the time of writing, the latest version of Ruby is Ruby 2.x where ‘x’represents the minor version numbers used differentiate specific updates toRuby 2 (e.g. Ruby 2.1.6, Ruby 2.2.2 and so on). Many programmers are stillusing earlier versions of Ruby, however, such as Ruby 1.8 or 1.9. In most cases,the syntax and behaviour of Ruby 1.x (from at least version 1.8) and Ruby 2.xare identical. That is not to say that there are no important differences but atthis stage they need not concern us. In most cases the code described in thisbook will run identically in Ruby 1.8, 1.9 and 2.x.

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 9Installing A Ruby Editor or IDEWhile you could write Ruby programs in a simple text editor and run themfrom the command prompt, it is a good idea to use (at the very minimum) aRuby editor with syntax code coloring. If you are really serious about Rubyyou should think about using a Ruby IDE that offers features such asIntelliSense (code completion) and integrated debugging. Here are a fewpossibilities SCITEFree programmers’ editor with some basic support for Ruby editing:http://www.scintilla.org/SciTE.htmlKOMODO EDITFree editor for multiple programming languages including Ruby. A morepowerful commercial edition, Komodo IDE, is also available. Runs onWindows, Linux, Mac OS ial cross-platform IDE that is tailored for Ruby On Rails users. Runson Windows, Linux, Mac OS X:http://www.jetbrains.com/ruby/

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 10TEXTMATECommercial programmers’ editor, with Ruby coding features, for Mac users:http://macromates.com/

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 11Get The Source Code Of The Sample ProgramsAll the programs in every chapter in this book are available as a Zip archivewhich may be downloaded /The-Little-Book-OfRuby.html.When you unzip the programs you will find that they are grouped intoa set of directories – one for each chapter. You may load the individual Rubyprograms one at a time.Running Ruby ProgramsIt is often useful to keep a Command window open in the source directorycontaining your Ruby program files. Assuming that the Ruby interpreter iscorrectly pathed on your system, you will then be able to run programs byentering ruby program name like this:ruby helloworld.rb

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 12Running Ruby From a Command PromptON WINDOWSClick the Start menu. In the Run or Search text entry field enter:cmdThis should open a text-mode window. You can now change to thedirectory containing the Ruby program you wish to run. To change directoryenter cd followed by the directory name. e.g. cd C:\myrubyprogramsON MAC OS XYou need to open a ‘Terminal’ window. Double-click your hard-drive (e.g.Macintosh HD). Open the Applications folder. Then open the Utilities folder.Double-click the Terminal icon. This will open a window into which you canenter commands to run Ruby. To change directory enter cd followed by thedirectory name. e.g. cd /myrubyprograms.

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 13TIP: OPEN A COMMAND WINDOW IN THE SELECTED FOLDEROn Windows and OS X it is possible to navigate to a folder usingthe system File Browser and open a Command Window orTerminal on that folder. This is much simpler and quicker thannavigating directories from the system prompt. This is how to dothat:WindowsOpen the Windows Explorer. Navigate to a specificdirectory. Enter CMD in the Explorer address bar. This opens acommand window in the selected directory.OS XBefore you can do this on a Mac you need to set an option asfollows: Go to System Preferences, then select Keyboard and Services.In the Keyboard settings dialog, scroll down to the entry labelled‘New Terminal at Folder’. Check it. Now in Finder you can navigateto the folder you need (the one containing your Ruby program) –Right click the folder. The popup menu will contain an item called‘New Terminal at Folder’, When selected this opens a Terminal on thecurrent folder.

The Little Book Of Ruby :: Welcome To The Little Book Of Ruby :: www.bitwisebooks.com :: page 14How To Use This BookThis book is a step-by-step tutorial to programming in Ruby and you canfollow it chapter by chapter, reading the text and running the sampleprograms. On the other hand, if you prefer to ‘dip in’, you may want to try outsome of the programs in whichever order takes your fancy; then refer back tothe text for explanations. There are no monolithic applications in this book –just small, self-contained sample programs – so it’s easy to skip from chapterto chapter if you wish Making Sense Of The TextIn The Little Book Of Ruby, any Ruby source code is written like this:def saysomethingputs( "Hello" )endWhen there is a sample program to accompany the code, the programname is shown in a little box like this:helloname.rbExplanatory notes (which generally provide some hints or give a morein-depth explanation of some point mentioned in the text) are shown in ashaded box like this:This is an explanatory note. You can skip it if you like – but if youdo so, you may miss something of interest !

The Little Book Of Ruby :: www.bitwisebooks.com :: page 15Chapter OneINWHICH WE TIE UP SOME STRINGS, ADD UP SOME NUMBERS, MESS ABOUT WITHMETHODS AND DIAGNOSE SOME CONDITIONS From the fact that you are reading this, it is safe to deduce that you want toprogram Ruby – and, if you are anything like me, you will be impatient to geton with it. OK, let’s not hang around. I’ll assume that you already have Rubyinstalled. If not, you’ll need to do that first, as explained in the Introduction Now, let’s start coding. Fire up your editor and enter the following:helloworld.rbputs 'Hello world'Here puts is the name of a function or ‘method’ that can display or‘put’ a string such as 'Hello world'. Run this program (as explained earlier). Ifyou are using an editor which lacks an interactive console, you should run thisprogram from the command prompt. To do this, open a command window orTerminal and navigate to the directory containing the source code then enterruby followed by the program name, like this:ruby helloworld.rbAll being well, Ruby should display: Hello world.

The Little Book Of Ruby :: www.bitwisebooks.com :: page 16This must just about the shortest ‘Hello world’ program in the historyof programming so we’ll immediately move on to a way of getting input fromthe user The obvious next step is to ‘get’ a string. The Ruby method for this isgets.uppercase.rbOBJECTS AND METHODSBefore we go any further, let me explain what a method is. Tounderstand that, we also need to be clear on what an object is.Ruby is a highly Object Oriented programming (OOP)language. Everything from an integer to a string is considered to bean object. And each object has built in functions or ‘methods’ whichcan be used to do various useful things. To use a method, yougenerally need to put a dot after the object name, then append themethod name. For example, Here I am using the upcase method todisplay the string, “hello world” in uppercase:puts( "hello world".upcase )But some methods such as puts and gets are availableeverywhere and don’t need to be associated with a specific object.Technically speaking, these methods are provided by Ruby’sKernel module and they are included in all Ruby objects (Modulesand inclusion are explained in Chapter Nine). When you run aRuby application, an object called main is automatically created andthis object provides access to the Kernel methods.

The Little Book Of Ruby :: www.bitwisebooks.com :: page 17The helloname.rb program prompts the user for his or her name – let’ssuppose it’s “Fred” - and then displays a greeting: “Hello Fred”. Here’s thecode:helloname.rbprint( 'Enter your name: ' )name gets()puts( "Hello #{name}" )While this is still very simple, there are a few details that need to beexplained. First, notice that I’ve used print rather than puts to display theprompt. This is because puts adds a linefeed at the end whereas print doesnot; in the present case I want the cursor to remain on the same line as theprompt.On the next line I use gets() to read in a string when the user pressesEnter. This string is assigned to the variable, name. I have not predeclared thisvariable, nor have I specified its type. In Ruby you can create variables as youneed them and Ruby ‘infers’ their types. Here I have assigned a string to nameso Ruby knows that the type of the name variable must be a string.NOTE: Ruby is case sensitive. A variable called myvar is differentfrom one called myVar. A variable such as name in our sampleproject must begin with a lowercase character.Incidentally, the parentheses following gets() are optional as are theparentheses (or ‘round brackets’) enclosing the strings after print and puts;the code would run just the same if you removed the parentheses. Roundbrackets help to avoid potential ambiguity in code and, in some cases, theRuby interpreter will warn you if you omit them.

The Little Book Of Ruby :: www.bitwisebooks.com :: page 18While some Ruby programmers like to omit parentheses wheneverpossible, I am not one of them; you will, therefore, find parentheses usedliberally in my programs.Strings and Embedded EvaluationThe last line in the helloname.rb program is rather interesting:puts( "Hello #{name}" )Here the name variable is embedded into the string itself. This is doneby placing the variable between two curly braces preceded by a hash (‘pound’)character #{ }. This kind of ‘embedded’ evaluation only works with stringsdelimited by double quotes.It isn’t only variables which can be embedded in double-quoted strings.You can also embed non-printing characters such as newlines "\n" and tabs"\t".You can even embed bits of program code and mathematicalexpressions. Let’s assume that you have a method called showname, whichreturns the string ‘Fred’. The double-quoted string shown below would, in theprocess of evaluation, call the showname method and, as a result, it woulddisplay the string “Hello Fred”:string eval.rbputs "Hello #{showname}"See if you can figure out what would be displayed by the following:puts( "\n\t#{(1 2) * 3}" )

The Little Book Of Ruby :: www.bitwisebooks.com :: page 19Run the string eval.rb program to see if you were right.COMMENTSLines beginning with a # character are treated as comments (theyare ignored by the Ruby interpreter):# This is a commentMethodsA method is so called because it provides a method (that is, ‘a way’) for anobject to respond to messages. In OOP terminology, you send a message to anobject by asking it to do something. So let’s imagine that you have an objectcalled ob which has a method called saysomething. This is how you wouldsend a saysomething message to the object:object.rbob.saysomethingLet’s suppose that the saysomething method looks like this:def saysomethingputs( "Hello" )endThe result is, that when you send ob a saysomething message itresponds by running the saysomething method which displays “Hello”.

The Little Book Of Ruby :: www.bitwisebooks.com :: page 20OK, so that’s the ‘pure OOP’ way of describing this. A not-so-pure OOPway of describing it would be to say that saysomething is like a function orsubroutine which is bound to the object and can be called using dot notation:ob.saysomething.method.rbIn Ruby a method is declared with the keyword def followed by amethod name which should begin with a lowercase letter, like this:def showstringputs( "Hello" )endYou may optionally put one or more arguments, separated by commas,after the method name:def showname( aName )puts( "Hello #{aName}" )enddef return name( aFirstName, aSecondName )return "Hello #{aFirstName} #{aSecondName}"endThe parentheses around the arguments are optional. The followingsyntax is also permissible:def return name2 aFirstName, aSecondNamereturn "Hello #{aFirstName} #{aSecondName}"endAs explained previously, for the sake of clarity, I am very muchprejudiced in favour of parentheses but you can omit them if you wish.

The Little Book Of Ruby :: www.bitwisebooks.com :: page 21mainob.rbIf methods belong to objects, which object owns any ‘free-standing’methods (such as showname in method.rb) that you write in yourcode? As I mentioned earlier, Ruby automatically creates an objectnamed main when you run a program and it is to this object thatany free-standing methods belong.NumbersNumbers are just as easy to use as strings. For example, let’s suppose youwant to calculate the selling price or ‘grand total’ of some item based on its extax value or ‘subtotal’.To do this you would need to multiply the subtotal by the applicabletax rate and add the result to the value of the subtotal. Assuming the subtotalto be 100 and the tax rate to be 17.5%, this Ruby code would do thecalculation and display the result:subtotal 100.00taxrate 0.175tax subtotal * taxrateputs "Tax on #{subtotal} is #{tax}, so grand total is #{subtotal tax}"Obviously, it would be more useful if it could perform calculations on avariety of subtotals rather than calculating the same value time after time!Here is a simple version of a Tax Calculator that prompts the user to enter asubtotal:

The Little Book Of Ruby :: www.bitwisebooks.com :: page 22taxrate 0.175print "Enter price (ex tax): "s getssubtotal s.to ftax subtotal * taxrateputs "Tax on #{subtotal} is #{tax}, so grand total is #{subtotal tax}"Here to f is a method of the String class (and the variable s isassigned a string entered by the user). The to f method attempts to convertthe string to a floating point number. For example, the string “145.45” wouldbe converted to the floating point number, 145.45. If the string cannot beconverted, 0.0 is returned. So, for instance, "Hello world".to f wouldreturn 0.0.Testing a Condition: if thenThe problem with the simple tax calculator code shown above is that it acceptsminus subtotals and calculates minus tax on them – a situation upon which theGovernment is unlikely to look favourably! I therefore need to check for minusfigures and, when found, set them to zero. This is my new version of the code:tax calculator.rbtaxrate 0.175print "Enter price (ex tax): "s getssubtotal s.to fif (subtotal 0.0) thensubtotal 0.0endtax subtotal * taxrateputs "Tax on #{subtotal} is #{tax}, so grand total is #{subtotal tax}"

The Little Book Of Ruby :: www.bitwisebooks.com :: page 23The Ruby if test is similar to an if test in other programminglanguages. Note, however, that the parentheses are once again optional, as isthe keyword then. However, if you were to write the following, with no linebreak after the test condition, the then would be obligatory:if (subtotal 0.0) then subtotal 0.0 endHowever, the end keyword that terminates the if block is not optional.Forget to add it and your code will not run.

The Little Book Of Ruby :: www.bitwisebooks.com :: page 24Chapter TwoDEFINING CLASSES, CREATING OBJECTS AND PEEKING INSIDE THEM So far we’ve used a number of ‘standard’ Ruby objects such as numbers andstrings. Let’s now see how to create new types of objects of our very own. Asin most other OOP languages, a Ruby object is defined by a class. The class islike a blueprint from which individual objects are constructed. This is a verysimple class:class MyClassendAnd this is how I would create a usable object from it:ob MyClass.newNot that I can do a great deal with my ob object – for the simple reasonthat I haven’t written any Ruby code in the MyClass class, from which it iscreated.object class.rbActually, if you create an ‘empty’ class like MyClass, the objectscreated from it will not be totally useless. All Ruby classesautomatically inherit the features of the Object class. So my obobject can make use of Object methods such as class (which tellsan object display its class).

The Little Book Of Ruby :: www.bitwisebooks.com :: page 25Try this:puts ob.classWhen run, this code displays the following:MyClassTo make MyClass a bit more useful, I need to give it a method or two.In this example (which was mentioned briefly in the last chapter), I’ve added amethod called saysomething:class MyClassdef saysomethingputs( "Hello" )endendNow, when I create a MyClass object, I can call this method in order toget that object to say “Hello”:ob MyClass.newob.saysomethingAnd this is the output:Hello

The Little Book Of Ruby :: www.bitwisebooks.com :: page 26Instances and Instance VariablesLet’s create some more useful objects. No home (or computer program) shouldbe without a dog. So let’s make ourselves a Dog class:class Dogdef set name( aName )@myname aNameendendNote that the class definition begins with the keyword class (all lowercase) and is followed by the name of the class itself, which must begin with anuppercase letter. My Dog class contains a single method, set name. This takesan incoming argument, aName. The body of the method assigns the value ofaName to a variable called @myname.Variables beginning with the @ character are ‘instance variables’ –that means that they belong to individuals objects – or ‘instances’ ofthe class. It is not necessary to pre-declare variables.I can create instances of the Dog class (that is, ‘dog objects’) by callingthe new method. Here I am creating two dog objects (remember that classnames begin uppercase letters; object names begin with lowercase letters):mydog Dog.newyourdog Dog.new

The Little Book Of Ruby :: www.bitwisebooks.com :: page 27At the moment, these two dogs have no names. So the next thing I do iscall the set name method to give them names:mydog.set name( 'Fido' )yourdog.set name( 'Bonzo' )Having given names to the dogs, I need to have some way to find outtheir names later on. Each dog needs to know its own name, so let’s give

Rails is a web development framework (a collection of code libraries and software tools) that uses Ruby as its programming language. It is popularly known as ‘Ruby On Rails’. While Rails is an impressive framework, it is not the be-all and end-all of Ruby. Indeed, if you decide to leap right into Rails

Related Documents:

RP 2K, Second Edition RP 2L, Third Edition RP 2M, First Edition Bul 2N, First Edition RP 2P, Second Edition RP 2Q, Second Edition RP 2R, First Edition RP 2T, First Edition Bul 2U, First Edition Bul 2V, First Edition Spec 2W, First Edition RP 2X, First Edition, with Supp 1 Spec 2Y, First Edition

4th Edition 2019 ISBN: 978-0-323-39304-1 Gray's Anatomy for Students Flash Cards, 4th Edition ISBN: 978-0-323-63917-0 Meisenberg & Simmons Principles of Medical Biochemistry, 4th Edition 2016 ISBN: 978-0-323-29616-8 Hansen Netter's Clinical Anatomy, 4th Edition 2018 ISBN: 978-0-323-53188-7 Loukas, Benninger

Fire Safe API 607 4th Edition Full Port Flanged Ball Valves Series FS50 Fire Safe API 607 4TH Edition Series FS50 flanged valves have been qualified by testing to API standards 607, 4th Edition. The valve design incorporates a secondary metal seat in the body, providing the requir

Fire Safe API 607 4th Edition Standard Port, Uni-Body Flanged Ball Valves Series FS54 Fire Safe API 607 4TH Edition Series FS54 flanged valves have been qualified by testing to API standards 607, 4th Edition. The valve design incorporates a secondary metal seat in the body, providing t

Fifth Edition 1977–1978 Sixth Edition 1979–1980 Seventh Edition 1981–1982 Eighth Edition 1983–1986 Ninth Edition 1987–1988 Tenth Edition 1989–1990 Eleventh Edition 1991–1992 Twelfth Edition 1993–1994 Thirteenth Edition 1995–1996 Fourteenth Edition 1997–1998 Fifteenth Edition

The “official” textbook, which is required, is Introduction to Electrodynamics, 4th Edition, (Cambridge University Press, 4th edition) by D. J. Griffiths. In the recent past, I used the 3rd edition. Students who wish to avoid purchasing the 4th edition may use the 3rd edition, if and only

4th edition, 1989 5th edition, 1994 6th edition, 2001 Spanish edition, 1978; 2nd edition Spanish edition, 2005; 5th edition Chinese edition, 1997 Test bank / Instructor's manual, 1989, 1994, 2001, 2012 Kazdin, A.E., & Rotella, C. (2013). The everyday parenting toolkit: The Kazdin Method for easy, step-by-step lasting change for you and your child.

The American Revolution, 1775-1781 Where was the American Revolution fought? Building a Professional Army nWashington’s task was to defendas much territory as possible: Relied on guerrilla tactics & avoided all-out-war with Britain Washington’s Continental Army served as the symbol of the “republican cause” But, colonial militias played a major role in “forcing” neutrals .