Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
RubyProgramming/Printversion Overview
RubyisanobjectorientedscriptinglanguagedevelopedbyYukihiroMatsumoto("Matz").ThemainwebsiteforRubyisrubylang.org(http://www.ruby lang.org/).DevelopmentbeganinFebruary1993andthefirstalphaversionofRubywasreleasedinDecember1994.Itwasdevelopedtobeanalternativeto scriptinglanguagessuchasPerlandPython. [1]RubyborrowsheavilyfromPerlandtheclasslibraryisessentiallyanobjectorientedreorganizationofPerl's functionality.RubyalsoborrowsfromLispandSmalltalk.WhileRubydoesnotborrowmanyfeaturesfromPython,readingthecodeforPythonhelpedMatz developRuby. [1] MacOSXcomeswithRubyalreadyinstalled.MostLinuxdistributionseithercomewithRubypreinstalledorallowyoutoeasilyinstallRubyfromthe distribution'srepositoryoffreesoftware.YoucanalsodownloadandinstallRubyonWindows.ThemoretechnicallyadeptcandownloadtheRubysource code[2]andcompileitformostoperatingsystems,includingUnix,DOS,BeOS,OS/2,Windows,andLinux. [3]
Features
RubycombinesfeaturesfromPerl,Smalltalk,Eiffel,Ada,Lisp,andPython. [3]
ObjectOriented
Rubygoestogreatlengthstobeapurelyobjectorientedlanguage.EveryvalueinRubyisanobject,eventhemostprimitivethings:strings,numbersand even t r u e and f a l s e .Everyobjecthasa classandeveryclasshasone superclass.Attherootoftheclasshierarchyistheclass O b j e c t ,fromwhichallother classesinherit. Everyclasshasasetof methodswhichcanbecalledonobjectsofthatclass.Methodsarealwayscalledonanobjecttherearenoclassmethods,as thereareinmanyotherlanguages(thoughRubydoesagreatjoboffakingthem). Everyobjecthasasetof instancevariableswhichholdthestateoftheobject.Instancevariablesarecreatedandaccessedfromwithinmethodscalledonthe object.Instancevariablesarecompletelyprivatetoanobject.Nootherobjectcanseethem,notevenotherobjectsofthesameclass,ortheclassitself.All communicationbetweenRubyobjectshappensthroughmethods.
Mixins
Inadditiontoclasses,Rubyhas modules.Amodulehasmethods,justlikeaclass,butithasnoinstances.Instead,amodulecanbeincluded,ormixedin, toaclass,whichaddsthemethodsofthatmoduletotheclass.Thisisverymuchlikeinheritancebutfarmoreflexiblebecauseaclasscanincludemany differentmodules.Bybuildingindividualfeaturesintoseparatemodules,functionalitycanbecombinedinelaboratewaysandcodeeasilyreused.Mixinshelp keepRubycodefreeofcomplicatedandrestrictiveclasshierarchies.
Dynamic
en.wikibooks.org/wiki/Ruby_Programming/Print_version 1/126
10/24/13
Rubyisavery dynamicprogramminglanguage.Rubyprogramsarentcompiled,inthewaythatCorJavaprogramsare.Alloftheclass,moduleandmethod definitionsinaprogramarebuiltbythecodewhenitisrun.Aprogramcanalsomodifyitsowndefinitionswhileitsrunning.Eventhemostprimitiveclassesof thelanguagelikeStringandIntegercanbeopenedupandextended.Rubyistscallthis monkeypatchinganditsthekindofthingyoucantgetawaywithin mostotherlanguages. VariablesinRubyaredynamicallytyped,whichmeansthatanyvariablecanholdanytypeofobject.Whenyoucallamethodonanobject,Rubylooksupthe methodbynamealoneitdoesn'tcareaboutthetypeoftheobject.Thisiscalled ducktypinganditletsyoumakeclassesthatcanpretendtobeother classes,justbyimplementingthesamemethods.
SingletonClasses
WhenIsaidthateveryRubyobjecthasaclass,Ilied.Thetruthis,everyobjecthas twoclasses:aregularclassanda singletonclass.Anobjectssingleton classisanamelessclasswhoseonlyinstanceisthatobject.Everyobjecthasitsveryownsingletonclass,createdautomaticallyalongwiththeobject. Singletonclassesinheritfromtheirobjectsregularclassandareinitiallyempty,butyoucanopenthemupandaddmethodstothem,whichcanthenbe calledontheloneobjectbelongingtothem.ThisisRubyssecrettricktoavoidclassmethodsandkeepitstypesystemsimpleandelegant.
Metaprogramming
Rubyissoobjectorientedthatevenclasses,modulesandmethodsarethemselvesobjects!Everyclassisaninstanceoftheclass C l a s s andeverymoduleis aninstanceoftheclass M o d u l e .Youcancalltheirmethodstolearnaboutthemorevenmodifythem,whileyourprogramisrunning.Thatmeansthatyoucan useRubycodetogenerateclassesandmodules,atechniqueknownas metaprogramming.Usedwisely,metaprogrammingallowsyoutocapturehighly abstractdesignpatternsincodeandimplementthemaseasilyascallingamethod.
Flexibility
InRuby,everythingismalleable.Methodscanbeaddedtoexistingclasseswithoutsubclassing,operatorscanbeoverloaded,andeventhebehaviorofthe standardlibrarycanberedefinedatruntime.
Variablesandscope
YoudonotneedtodeclarevariablesorvariablescopeinRuby.Thenameofthevariableautomaticallydeterminesitsscope. xislocalvariable(orsomethingbesidesavariable). $xisaglobalvariable. @xisaninstancevariable. @@xisaclassvariable.
Blocks
BlocksareoneofRubysmostuniqueandmostlovedfeatures.Ablockisapieceofcodethatcanappearafteracalltoamethod,likethis:
l a u n d r y _ l i s t . s o r td o| a , b |
en.wikibooks.org/wiki/Ruby_Programming/Print_version 2/126
10/24/13
a . c o l o r< = >b . c o l o r e n d
Theblockiseverythingbetweenthe d o andthe e n d .Thecodeintheblockisnotevaluatedrightaway,ratheritispackagedintoanobjectandpassedtothe s o r t methodasanargument.Thatobjectcanbecalledatanytime,justlikecallingamethod.The s o r t methodcallstheblockwheneveritneedstocompare twovaluesinthelist.Theblockgivesyoualotofcontroloverhow s o r t behaves.Ablockobject,likeanyotherobject,canbestoredinavariable,passedalong toothermethods,orevencopied. Manyprogramminglanguagessupportcodeobjectslikethis.Theyrecalled closuresandtheyareaverypowerfulfeatureinanylanguage,buttheyare typicallyunderusedbecausethecodetocreatethemtendstolookuglyandunnatural.ARubyblockissimplyaspecial,cleansyntaxforthecommoncaseof creatingaclosureandpassingittoamethod.ThissimplefeaturehasinspiredRubyiststouseclosuresextensively,inallsortsofcreativenewways.
Advancedfeatures
Rubycontainsmanyadvancedfeatures. Exceptionsforerrorhandling. Amarkandsweepgarbagecollectorinsteadofreferencecounting. OSindependentthreading,whichallowsyoutowritemultithreadedapplicationsevenonoperatingsystemssuchasDOS.(thisfeaturewilldisappearin 1.9,whichwillusenativethreads) YoucanalsowriteextensionstoRubyinCorembedRubyinothersoftware.
References
1. a b BruceStewart(November29,2001)."AnInterviewwiththeCreatorofRuby".O'Reilly. http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html.Retrieved20060911. 2. "DownloadRuby".http://www.rubylang.org/en/downloads/.Retrieved20060911. 3. a b "AboutRuby".http://www.rubylang.org/en/about/.Retrieved20060911.
InstallingRuby
RubycomespreinstalledonMacOSXandmanyLinuxdistributions.Inaddition,itisavailableformostotheroperatingsystems,includingMicrosoftWindows. TofindtheeasiestwaytoinstallRubyforyoursystem,followthedirectionsbelow.YoucanalsoinstallRubybycompilingthesourcecode,whichcanbe downloadedfromtheRubywebsite(http://www.rubylang.org/en/downloads/).
Operatingsystems
MacOSX
en.wikibooks.org/wiki/Ruby_Programming/Print_version 3/126
10/24/13
RubycomespreinstalledonMacOSX.Tocheckwhatversionisonyoursystem: 1. LaunchtheTerminalapplication,whichislocatedinthe"Utilities"folder,under"Applications". 2. Atthecommandline,enter: r u b yv IfyouwanttoinstallamorerecentversionofRuby,youcan: BuythelatestversionofMacOSX,whichmayhaveamorerecentversionofRuby. InstallRubyusingRVM(http://beginrescueend.com/).(Thisisthemostpopularwaybecauseyoucanmanagerubyversionsandinstallmanyotherruby packages) InstallRubyusingFink. InstallRubyusingMacPorts. InstallRubyusingHomebrew.
Linux
RubycomespreinstalledonmanyLinuxsystems.TocheckifRubyisinstalledonyoursystem,fromtheshellrun: r u b yv Ifrubyisnotinstalled,orifyouwanttoupgradetothelatestversion,youcanusuallyinstallRubyfromyourdistribution'ssoftwarerepository.Directionsfor somedistributionsaredescribedbelow. Debian/Ubuntu OnDebianandUbuntu,installRubyusingeitherthegraphicaltoolSynaptic(onDebian,onlyifitisinstalleditisincludedwithUbuntu)orthecommandline toolapt. FedoraCore IfyouhaveFedoraCore5orlater,youcaninstallRubyusingthegraphicaltoolPirut. [1]Otherwise,youcaninstallRubyusingthecommandlinetoolyum.
en.wikibooks.org/wiki/Ruby_Programming/Print_version
4/126
10/24/13
Windows
RubydoesnotcomepreinstalledwithanyversionofMicrosoftWindows.However,thereareseveralwaystoinstallRubyonWindows. DownloadandinstalloneofthecompiledRubybinariesfromtheRubywebsite(http://www.rubylang.org/en/downloads/). DownloadandruntheoneclickRubyInstaller(http://rubyinstaller.org/). InstallCygwin,acollectionoffreesoftwaretoolsavailableforWindows.Duringtheinstall,makesurethatyouselectthe"ruby"package,locatedinthe "Devel,Interpreters"category. Windowsisslow CurrentlyRubyonwindowsisabitslow.Rubyisn'toptimizedforwindows,becausemostcoredevelopersuseLinux.Though1.9.2passesalmostallcoretests onwindows. Mostoftoday'sslowdownisbecausewhenrubydoesa
r e q u i r e' x x x '
10/24/13
NBthatJrubytendstorunfaster(http://betterlogic.com/roger/?p=2841)butstartslower,onwindows,thanitsMRIcousins.Rubiniusiscurrentlynotyet windowscompatible.
BuildingfromSource
Ifyourdistrodoesn'tcomewitharubypackageoryouwanttobuildaspecificversionofrubyfromscratch,pleaseinstallitbyfollowingthedirectionshere (http://svn.rubylang.org/repos/ruby/trunk/README).Downloadfromhere(http://www.rubylang.org/en/downloads/).
Compileoptions
Buildingwithdebugsymbols
Ifyouwanttoinstallitwithdebugsymbolsbuiltin(andareusinggccsoeitherLinux,cygwin,ormingw).
. / c o n f i g u r ee n a b l e s h a r e do p t f l a g s = " O 0 "d e b u g f l a g s = " g 3g g d b "
Optimizations
Notethatwith1.9youcanpassit d i s a b l e i n s t a l l d o c tohaveitbuildfaster. TosettheGCtonotrunasfrequently(whichtendstoprovideafasterexperienceforlargerprograms,likerdocandrails),precedeyourbuildwith
$e x p o r tC C F L A G S = D G C _ M A L L O C _ L I M I T = 8 0 0 0 0 0 0 0
thoughyoumightbeabletoalternatelyputthoseinasoptordebugflags,aswell.
TestingInstallation
Theinstallationcanbetestedeasily.
$r u b yv
Thisshouldreturnsomethinglikethefollowing:
r u b y1 . 8 . 7( 2 0 0 9 0 6 1 2p a t c h l e v e l1 7 4 )[ i 4 8 6 l i n u x ]
Ifthisshowsup,thenyouhavesuccessfullyinstalledRuby.However,ifyougetsomethinglikethefollowing:
en.wikibooks.org/wiki/Ruby_Programming/Print_version
6/126
10/24/13
b a s h :r u b y :c o m m a n dn o tf o u n d
ThenyoudidnotsuccessfullyinstallRuby.
References
1. "yum".FedoraWiki.http://fedoraproject.org/wiki/Tools/yum.Retrieved20060913.
Rubyeditors
AlthoughyoucanwriteRubyprogramswithanyplaintexteditor,sometexteditorshaveadditionalfeaturestoaidtheRubyprogrammer.Themostcommonis syntaxhighlighting. Here(https://spreadsheets.google.com/ccc?key=0Al_hzYODcgxwdG9tUFhqcVVoUDVaLTlqT2YtNjV1N0E&hl=en#gid=1)isaspreadsheetofthevarious optionsavailable.
Notationconventions
Commandlineexamples
Inthistutorial,examplesthatinvolverunningprogramsonthecommandlinewillusethedollarsigntodenotetheshellprompt.Thepartoftheexamplethat youtypewillappear bold.Sincethedollarsigndenotesyourshellprompt,youshould not typeitin. Forexample,tocheckwhatversionofRubyisonyoursystem,run:
$r u b yv
10/24/13
RunningRubyscripts
Forsimplicity,thefollowingconventionisusedtoshowaRubyscriptbeingrunfromtheshellprompt.
$h e l l o w o r l d . r b H e l l ow o r l d
However,theactualsyntaxthatyouwillusetorunyourRubyscriptswillvarydependingonyouroperatingsystemandhowitissetup.Pleasereadthroughthe ExecutableRubyscriptssectionoftheHelloworldpagetodeterminethebestwaytorunRubyscriptsonyoursystem.
Runningirb
Rubytypicallyinstallswith"interactiveruby"(irb)installedalongwithit.ThisisaREPLthatallowsyoutoexperimentwithRuby,forexample:
$i r b > >3+4 = >7 > >' a b c ' = >" a b c "
InteractiveRuby
WhenlearningRuby,youwilloftenwanttoexperimentwithnewfeaturesbywritingshortsnippetsofcode.Insteadofwritingalotofsmalltextfiles,youcan use i r b ,whichisRuby'sinteractivemode.
Runningirb
Run i r b fromyourshellprompt.
$i r bs i m p l e p r o m p t > >
Asimple i r b sessionmightlooklikethis.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 8/126
10/24/13
Cygwinusers
IfyouuseCygwin'sBashshellonMicrosoftWindows,butarerunningthenativeWindowsversionofRubyinsteadofCygwin'sversionofRuby,readthis section. Torunthenativeversionof i r b insideofCygwin'sBashshell,run i r b . b a t . Bydefault,Cygwin'sBashshellrunsinsideoftheWindowsconsole,andthenativeWindowsversionof i r b . b a t shouldworkfine.However,ifyourunaCygwin shellinsideofCygwin'srxvtterminalemulator,then i r b . b a t willnotrunproperly.Youmusteitherrunyourshell(and i r b . b a t )insideoftheWindowsconsoleor installandrunCygwin'sversionofRuby.
Understandingirboutput
i r b printsoutthereturnvalueofeachlinethatyouenter.Incontrast,anactualRubyprogramonlyprintsoutputwhenyoucallanoutputmethodsuchas p u t s .
Forexample:
$i r bs i m p l e p r o m p t > >x = 3 = >3 > >y = x * 2 = >6 > >z = y / 6 = >1 > >x = >3 > >e x i t
10/24/13
IfyouwanttoprintoutthevalueofavariableinaRubyprogram,usethe p u t s method.
x = 3 p u t sx
MailingListFAQ
Etiquette
ThereisalistofBestPractices[1].
WhatistheBesteditor?
SeveraleditorsexistforRuby. Commercial:TheeditorofpreferenceonOSXisTextmate.RubyMinehasalsoreceivedgoodreviewed[2] Free:NetBeansoffersaversionwithRubysupport.RadRailsisaportofeclipsetosupportRubysyntax.EclipsehasapluginDLTKthatoffersrubysupport [3]. OnwindowsforrailsprojectsthereisRoRed. Seesomemore(http://wiki.github.com/rdp/ruby_tutorials_core/rubytalkfaq)questionsanswered. 1. http://blog.rubybestpractices.com/posts/jamesbritt/and_your_Mom_too.html 2. http://www.rubyinside.com/rubymine10rubyide1818.html 3. http://www.infoq.com/news/2007/08/eclipsedltk09
BasicRubyHelloworld
Theclassic"helloworld"programisagoodwaytogetstartedwithRuby.
Helloworld
Createatextfilecalled h e l l o w o r l d . r b containingthefollowingcode:
p u t s' H e l l ow o r l d '
en.wikibooks.org/wiki/Ruby_Programming/Print_version
10/126
10/24/13
Nowrunitattheshellprompt.
$r u b yh e l l o w o r l d . r b H e l l ow o r l d
orexecuteonline(http://codepad.org/8OlSc6Sf) Youcanalsoruntheshort"helloworld"programwithoutcreatingatextfileatall.Thisiscalledaoneliner.
$r u b ye" p u t s' H e l l ow o r l d ' " H e l l ow o r l d
Comments
LikePerl,Bash,andCShell,Rubyusesthehashsymbol(alsocalledPoundSign,numbersign,Square,oroctothorpe)forcomments.Everythingfromthe hashtotheendofthelineisignoredwhentheprogramisrunbyRuby.Forexample,here'sour h e l l o w o r l d . r b programwithcomments.
#M yf i r s tR u b yp r o g r a m #O nm yw a yt oR u b yf a m e&f o r t u n e ! p u t s' H e l l ow o r l d '
Youcanappendacommenttotheendofalineofcode,aswell.EverythingbeforethehashistreatedasnormalRubycode.
p u t s' H e l l ow o r l d ' #P r i n to u t" H e l l ow o r l d "
Youcanalsocommentseverallinesatatime:
= b e g i n T h i sp r o g r a mw i l l p r i n t" H e l l ow o r l d " . = e n d
en.wikibooks.org/wiki/Ruby_Programming/Print_version 11/126
10/24/13
p u t s' H e l l ow o r l d '
executeonline(http://codepad.org/o5UAYMcw)
ExecutableRubyscripts
Typingtheword r u b y eachtimeyourunaRubyscriptistedious.Toavoiddoingthis,followtheinstructionsbelow.
Unixlikeoperatingsystems
InUnixlikeoperatingsystemssuchasLinux,MacOSX,andSolarisyouwillwanttomarkyourRubyscriptsasexecutableusingthe c h m o d command.This alsoworkswiththeCygwinversionofRuby.
$c h m o d+ xh e l l o w o r l d . r b
10/24/13
Windows
IfyouinstallthenativeWindowsversionofRubyusingtheRubyOneClickInstaller(http://www.rubylang.org/en/downloads/),thentheinstallerhassetup WindowstoautomaticallyrecognizeyourRubyscriptsasexecutables.Justtypethenameofthescripttorunit.
$h e l l o w o r l d . r b H e l l ow o r l d
10/24/13
BasicRubyStrings
LikePython,Java,andthe.NETFramework,RubyhasabuiltinStringclass.
Stringliterals
OnewaytocreateaStringistousesingleordoublequotesinsideaRubyprogramtocreatewhatiscalledastringliteral.We'vealreadydonethiswithour "helloworld"program.Aquickupdatetoourcodeshowstheuseofbothsingleanddoublequotes.
p u t s' H e l l ow o r l d ' p u t s" H e l l ow o r l d "
Singlequotes
Singlequotesonlysupporttwoescapesequences.
\ ' singlequote \ \ singlebackslash
Exceptforthesetwoescapesequences,everythingelsebetweensinglequotesistreatedliterally.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 14/126
10/24/13
Doublequotes
Doublequotesallowformanymoreescapesequencesthansinglequotes.TheyalsoallowyoutoembedvariablesorRubycodeinsideofastringliteralthis iscommonlyreferredtoasinterpolation.
p u t s" E n t e rn a m e " n a m e=g e t s . c h o m p p u t s" Y o u rn a m ei s# { n a m e } "
Escapesequences
Belowaresomeofthemorecommonescapesequencesthatcanappearinsideofdoublequotes.
\ " doublequote \ \ singlebackslash \ a bell/alert \ b backspace \ r carriagereturn \ n newline \ s space \ t tab
Tryoutthisexamplecodetobetterunderstandescapesequences.
p u t s" H e l l o \ t \ t w o r l d " p u t s" H e l l o \ b \ b \ b \ b \ b G o o d b y ew o r l d " p u t s" H e l l o \ r S t a r to v e rw o r l d " p u t s" 1 .H e l l o \ n 2 .W o r l d "
Theresult:
$d o u b l e q u o t e s . r b H e l l o w o r l d G o o d b y ew o r l d S t a r to v e rw o r l d 1 .H e l l o 2 .W o r l d
en.wikibooks.org/wiki/Ruby_Programming/Print_version
15/126
10/24/13
puts
We'vebeenusingthe p u t s functionquiteabittoprintouttext.Whenever p u t s printsouttext,itautomaticallyprintsoutanewlineafterthetext.Forexample, trythefollowingcode.
p u t s" S a y " ," h e l l o " ," t o " ," t h e " ," w o r l d "
Theresult:
$h e l l o w o r l d . r b S a y h e l l o t o t h e w o r l d
print
Incontrast,Ruby's p r i n t functiononlyprintsoutanewlineifyouspecifyone.Forexample,tryoutthefollowingcode.Weincludeanewlineattheendof p r i n t 's argumentlistsothattheshellpromptappearsonanewline,afterthetext.
p r i n t" S a y " ," h e l l o " ," t o " ," t h e " ," w o r l d " ," \ n "
Theresult:
$h e l l o w o r l d . r b S a y h e l l o t o t h e w o r l d
Thefollowingcodeproducesthesameoutput,withallthewordsruntogether.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 16/126
10/24/13
p r i n t" S a y " p r i n t" h e l l o " p r i n t" t o " p r i n t" t h e " p r i n t" w o r l d " p r i n t" \ n "
Seealso
Stringliterals(http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#Strings)
BasicRubyAlternatequotes
InRuby,there'smorethanonewaytoquoteastringliteral.MuchofthiswilllookfamiliartoPerlprogrammers.
Alternatesinglequotes
Let'ssayweareusingsinglequotestoprintoutthefollowingpath.
p u t s' c : \ b u ss c h e d u l e s \ n a p o l e a n \ t h ep o r t l a n db u ss c h e d u l e . t x t '
Escapingtheapostrophesmakesthecodelessreadableandmakesitlessobviouswhatwillprintout.Luckily,inRuby,there'sabetterway.Youcanusethe % q operatortoapplysinglequotingrules,butchooseyourowndelimitertomarkthebeginningandendofthestringliteral.
p u t s% q ! c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t ! p u t s% q / c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t / p u t s% q ^ c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t ^ p u t s% q ( c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t ) p u t s% q { c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t } p u t s% q < c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t >
10/24/13
p u t s% q # c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' s\ # 9b u ss c h e d u l e . t x t #
Ifyouusematchingbracestodelimitthetext,however,youcannestbraces,withoutescapingthem.
p u t s% q ( c : \ n a p o l e a n ' sd o c u m e n t s \ t h e( b u s )s c h e d u l e . t x t ) p u t s% q { c : \ n a p o l e a n ' sd o c u m e n t s \ t h e{ b u s }s c h e d u l e . t x t } p u t s% q < c : \ n a p o l e a n ' sd o c u m e n t s \ t h e< b u s >s c h e d u l e . t x t >
Alternatedoublequotes
The % Q operator(noticethecaseofQin % Q )allowsyoutocreateastringliteralusingdoublequotingrules,butwithoutusingthedoublequoteasadelimiter.It worksmuchthesameasthe % q operator.
p r i n t% Q ^ S a y : \ t H e l l ow o r l d \ n \ t H e l l ow o r l d \ n ^ p r i n t% Q ( S a y : \ t H e l l ow o r l d \ n \ t H e l l ow o r l d \ n )
Justlikedoublequotes,youcaninterpolateRubycodeinsideofthesestringliterals.
n a m e=' C h a r l i eB r o w n ' p u t s% Q ! S a y" H e l l o , "# { n a m e } . ! p u t s% Q / W h a ti s" 4p l u s5 " ?A n s w e r :# { 4 + 5 } /
BasicRubyHeredocuments
Forcreatingmultiplelinestrings,Rubysupportsheredocuments(heredocs),afeaturethatoriginatedintheBourneshellandisalsoavailableinPerland PHP.
Heredocuments
Toconstructaheredocument,the < < operatorisfollowedbyanidentifierthatmarkstheendoftheheredocument.Theendmarkiscalledtheterminator.The linesoftextpriortotheterminatorarejoinedtogether,includingthenewlinesandanyotherwhitespace.
p u t s< < G R O C E R Y _ L I S T G r o c e r yl i s t
en.wikibooks.org/wiki/Ruby_Programming/Print_version 18/126
10/24/13
1 .S a l a dm i x . 2 .S t r a w b e r r i e s . * 3 .C e r e a l . 4 .M i l k . * *O r g a n i c G R O C E R Y _ L I S T
Theresult:
$g r o c e r y l i s t . r b G r o c e r yl i s t 1 .S a l a dm i x . 2 .S t r a w b e r r i e s . * 3 .C e r e a l . 4 .M i l k . * *O r g a n i c
Youcanalsohavemultipleheredocumentsinanargumentlist.Weaddedablanklineattheendofeachheredocumenttomaketheoutputmorereadable.
p u t s' P r o d u c e ' ,' ' ,< < P R O D U C E ,' D a i r y ' ,' ' ,< < D A I R Y ,' *O r g a n i c ' 1 .S t r a w b e r r i e s * 2 .B l u e b e r r i e s P R O D U C E 1 .Y o g u r t 2 .M i l k * 3 .C o t t a g eC h e e s e D A I R Y
en.wikibooks.org/wiki/Ruby_Programming/Print_version 19/126
10/24/13
Theresult:
$g r o c e r y l i s t . r b P r o d u c e 1 .S t r a w b e r r i e s * 2 .B l u e b e r r i e s D a i r y 1 .Y o g u r t 2 .M i l k * 3 .C o t t a g eC h e e s e *O r g a n i c
Wehavebeenusingthe p u t s functioninourexamples,butyoucanpassheredocumentstoanyfunctionthatacceptsStrings.
Indenting
Ifyouindentthelinesinsidetheheredocument,theleadingwhitespaceispreserved.However,theremustnotbeanyleadingwhitespacebeforethe terminator.
p u t s' G r o c e r yl i s t ' ,' ' ,< < G R O C E R Y _ L I S T 1 .S a l a dm i x . 2 .S t r a w b e r r i e s . 3 .C e r e a l . 4 .M i l k . G R O C E R Y _ L I S T
Theresult:
$g r o c e r y l i s t . r b G r o c e r yl i s t 1 .S a l a dm i x . 2 .S t r a w b e r r i e s . 3 .C e r e a l . 4 .M i l k .
10/24/13
2 .S t r a w b e r r i e s . 3 .C e r e a l . 4 .M i l k . G R O C E R Y _ L I S T
Note,however,thatthewhitespacebeforeeachlineoftext withintheheredocumentisstillpreserved.
$g r o c e r y l i s t . r b G r o c e r yl i s t 1 .S a l a dm i x . 2 .S t r a w b e r r i e s . 3 .C e r e a l . 4 .M i l k .
Quotingrules
Youmaywonderwhetherheredocumentsfollowsinglequotingordoublequotingrules.Iftherearenoquotesaroundtheidentifier,likeinourexamplesso far,thenthebodyoftheheredocumentfollowsdoublequotingrules.
n a m e=' C h a r l i eB r o w n ' p u t s< < Q U I Z S t u d e n t :# { n a m e } 1 . \ t Q u e s t i o n :W h a ti s4 + 5 ? \ t A n s w e r :T h es u mo f4a n d5i s# { 4 + 5 } Q U I Z
Theresult:
$q u i z . r b S t u d e n t :C h a r l i eB r o w n 1 . Q u e s t i o n :W h a ti s4 + 5 ? A n s w e r :T h es u mo f4a n d5i s9
Doublequotingrulesarealsofollowedifyouputdoublequotesaroundtheidentifier.However,donotputdoublequotesaroundtheterminator.
p u t s< < " Q U I Z " S t u d e n t :# { n a m e } 1 . \ t Q u e s t i o n :W h a ti s4 + 5 ?
en.wikibooks.org/wiki/Ruby_Programming/Print_version 21/126
10/24/13
\ t A n s w e r :T h es u mo f4a n d5i s# { 4 + 5 } Q U I Z
Tocreateaheredocumentthatfollowssinglequotingrules,placesinglequotesaroundtheidentifier.
p u t s< < ' B U S _ S C H E D U L E S ' c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t c : \ n e wd o c u m e n t s \ s a ms p a d e ' sb u ss c h e d u l e . t x t c : \ b u ss c h e d u l e s \ t h e# 9b u ss c h e d u l e . t x t B U S _ S C H E D U L E S
Theresult:
$b u s s c h e d u l e s . r b c : \ n a p o l e a n ' sd o c u m e n t s \ t o m o r r o w ' sb u ss c h e d u l e . t x t c : \ n e wd o c u m e n t s \ s a ms p a d e ' sb u ss c h e d u l e . t x t c : \ b u ss c h e d u l e s \ t h e# 9b u ss c h e d u l e . t x t
BasicRubyIntroductiontoobjects
LikeSmalltalk,Rubyisapureobjectorientedlanguageeverythingisanobject.Incontrast,languagessuchasC++andJavaarehybridlanguagesthat dividetheworldbetweenobjectsandprimitivetypes.Thehybridapproachresultsinbetterperformanceforsomeapplications,butthepureobjectoriented approachismoreconsistentandsimplertouse.
Whatisanobject?
UsingSmalltalkterminology,anobjectcandoexactlythreethings. 1. Holdstate,includingreferencestootherobjects. 2. Receiveamessage,frombothitselfandotherobjects. 3. Inthecourseofprocessingamessage,sendmessages,bothtoitselfandtootherobjects. Ifyoudon'tcomefromSmalltalkbackground,itmightmakemoresensetorephrasetheserulesasfollows: 1. Anobjectcancontaindata,includingreferencestootherobjects. 2. Anobjectcancontainmethods,whicharefunctionsthathavespecialaccesstotheobject'sdata. 3. Anobject'smethodscancall/runothermethods/functions.
Variablesandobjects
en.wikibooks.org/wiki/Ruby_Programming/Print_version 22/126
10/24/13
Let'sfireup i r b togetabetterunderstandingofobjects.
$i r bs i m p l e p r o m p t > >c o m e d i a n=" S t e p h e nC o l b e r t " = >" S t e p h e nC o l b e r t "
Methods
InRuby,methodsthatendwithanexclamationmark(alsocalleda"bang")modifytheobject.Forexample,themethod u p c a s e ! changesthelettersofaString touppercase.
> >c o m e d i a n . u p c a s e ! = >" S T E P H E NC O L B E R T "
en.wikibooks.org/wiki/Ruby_Programming/Print_version
23/126
10/24/13
Reassigningavariable
ButwhatifyourfavoritecomedianisnotStephenColbert?Let'spoint f a v o r i t e _ c o m e d i a n toanewobject.
> >f a v o r i t e _ c o m e d i a n=" J o nS t e w a r t " = >" J o nS t e w a r t "
Now,eachvariablepointstoadifferentobject.
en.wikibooks.org/wiki/Ruby_Programming/Print_version
24/126
10/24/13
Let'ssaythatwechangeourmindagain.Now,ourfavoritecomedianisEllenDeGeneres.
> >f a v o r i t e _ c o m e d i a n=" E l l e nD e G e n e r e s " = >" E l l e nD e G e n e r e s "
Now,novariablepointstothe" J o nS t e w a r t "Stringobjectanylonger.Hence,Rubywilldisposeofit.
BasicRubyRubybasics
Aswiththerestofthistutorial,weassumesomebasicfamiliaritywithprogramminglanguageconcepts(i.e.ifstatement,whileloops)andalsosomebasic understandingofobjectorientedprogramming.
Dealingwithvariables
en.wikibooks.org/wiki/Ruby_Programming/Print_version 25/126
10/24/13
We'lldealwithvariablesinmuchmoredepthwhenwetalkaboutclassesandobjects.Fornow,let'sjustsayyourbasiclocalvariablenamesshouldstartwith eitheralowercaseletteroranunderscore,andshouldcontainupperorlowercaseletters,numbers,andunderscorecharacters.Globalvariablesstartwitha $ .
Programflow
Rubyincludesaprettystandardsetofloopingandbranchingconstructs: i f , w h i l e and c a s e Forexample,here's i f inaction:
a=1 0*r a n d i fa<5 p u t s" # { a }l e s st h a n5 " e l s i fa>7 p u t s" # { a }g r e a t e rt h a n7 " e l s e p u t s" C h e e s es a n d w i c h ! " e n d
Notethatthe i f statementisalsoanexpressionitsvalueisthelastlineoftheblockexecuted.Therefore,thelineabovecouldalsohavebeenwrittenas
p u t s ( i fa<5t h e n" # { a }l e s st h a n5 "e l s e" # { a }g r e a t e rt h a n5 "e n d )
en.wikibooks.org/wiki/Ruby_Programming/Print_version
26/126
10/24/13
w h i l ea>5 a=1 0 * r a n d e n d
Therearesomeotherinterestingthingsgoingoninthisexample,butherethe c a s e statementisthecenterofattention.
Writingfunctions
InkeepingwithRuby'sallobjectorientedallthetimedesign,functionsaretypicallyreferredtoasmethods.Nodifference.We'llcovermethodsinmuchmore detailwhenwegettoobjectsandclasses.Fornow,basicmethodwritinglookssomethinglikethis(savethefollowingcodeinafilecalledfunc1.rb):
#D e m o n s t r a t eam e t h o dw i t hf u n c 1 . r b d e fm y _ f u n c t i o n (a) p u t s" H e l l o ,# { a } " r e t u r na . l e n g t h e n d l e n=m y _ f u n c t i o n (" G i r a f f e ") p u t s" M ys e c r e tw o r di s# { l e n }c h a r a c t e r sl o n g "
en.wikibooks.org/wiki/Ruby_Programming/Print_version
27/126
10/24/13
nowrunthescript:
$f u n c 1 . r b H e l l o ,G i r a f f e M ys e c r e tw o r di s7c h a r a c t e r sl o n g
Methodsaredefinedwiththe d e f keyword,followedbythefunctionname.Aswithvariables,localandclassmethodsshouldstartwithalowercaseletter. Inthisexample,thefunctiontakesoneargument(a )andreturnsavalue.Notethattheinputargumentsaren'ttyped(i.e. a neednotbeastring)...thisallows forgreatflexibilitybutcanalsocausealotoftrouble.Thefunctionalsoreturnsasinglevaluewiththe r e t u r n keyword.Technicallythisisn'tnecessarythe valueofthelastlineexecutedinthefunctionisusedasthereturnvaluebutmoreoftenthannotusing r e t u r n explicitlymakesthingsclearer. Aswithotherlanguages, R u b y supportsbothdefaultvaluesforargumentsandvariablelengthargumentlists,bothofwhichwillbecoveredinduetime.There's alsosupportforcodeblocks,asdiscussedbelow.
Blocks
OneveryimportantconceptinRubyisthecodeblock.It'sactuallynotaparticularlyrevolutionaryconceptanytimeyou'vewritten i f. . .{. . .} inCorPerl you'vedefinedacodeblock,butinRubyacodeblockhassomehiddensecretpowers... CodeblocksinRubyaredefinedeitherwiththekeywords d o . . e n d orthecurlybrackets { . . }
d o p r i n t" Il i k e" p r i n t" c o d eb l o c k s ! " e n d { p r i n t" M et o o ! " }
10/24/13
$b l o c k 2 . r b H e l l o ! H e l l o !
en.wikibooks.org/wiki/Ruby_Programming/Print_version
29/126
10/24/13
$b l o c k 1 . r b H e l l o ,T i g e r H e l l o ,G i r a f f e
whichwouldgive:
I t ' s5c h a r a c t e r sl o n g ! I t ' s7c h a r a c t e r sl o n g !
Rubyisreally,reallyobjectoriented
Rubyisveryobjectoriented.Everythingisanobjecteventhingsyoumightconsiderconstants.Thisalsomeansthatthevastmajorityofwhatyoumight consider"standardfunctions"aren'tfloatingaroundinsomelibrarysomewhere,butareinsteadmethodsofagivenvariable. Here'soneexamplewe'vealreadyseen:
3 . t i m e s{p u t s" H i ! "}
10/24/13
= >3 > >" g i r a f f e " . l e n g t h = >7 > >a=" g i r a f f e " = >" g i r a f f e " > >a . r e v e r s e = >" e f f a r i g "
TherewillbelotsoftimetoconsiderhowobjectorienteddesignfiltersthroughRubyinthecomingchapters.
BasicRubyDatatypes
RubyDataTypes
Asmentionedinthepreviouschapter,everythinginRubyisanobject.Everythinghasaclass.Don'tbelieveme?Tryrunningthisbitofcode:
h={ " h a s h ? "= >" y e p ,i t \ ' sah a s h ! " ," t h ea n s w e rt oe v e r y t h i n g "= >4 2 ,: l i n u x= >" f u nf o rc o d e r s . " } p u t s" S t r i n g ys t r i n gM c S t r i n g ! " . c l a s s p u t s1 . c l a s s p u t sn i l . c l a s s p u t sh . c l a s s p u t s: s y m b o l . c l a s s
displays
S t r i n g F i x n u m N i l C l a s s H a s h S y m b o l
Constants
We'llstartoffwithconstantsbecausethey'resimple.Twothingstorememberaboutconstants:
en.wikibooks.org/wiki/Ruby_Programming/Print_version
31/126
10/24/13
Symbols
Sodidyounoticesomethingweirdaboutthatfirstcodelisting?"Whattheheckwasthatcolonthingyabout?"Well,itjustsohappensthatRuby'sobject orientedwayshaveacost:lotsofobjectsmakeforslowcode.Everytimeyoutypeastring,Rubymakesanewobject.Regardlessofwhethertwostringsare identical,Rubytreatseveryinstanceasanewobject.Youcouldhave"livelongandprosper"inyourcodeonceandthenagainlateronandRubywouldn't evenrealizethatthey'reprettymuchthesamething.Hereisasampleirbsessionwhichdemonstratesthisfact:
i r b >" l i v el o n ga n dp r o s p e r " . o b j e c t _ i d = >5 0 7 7 7 2 2 6 8 i r b >" l i v el o n ga n dp r o s p e r " . o b j e c t _ i d = >5 0 7 7 7 6 5 3 8
Symbolsaredenotedbythecolonsittingoutinfrontofthem,likeso: : s y m b o l _ n a m e
Hashes
Hashesarelikedictionaries,inasense.Youhaveakey,areference,andyoulookituptofindtheassociatedobject,thedefinition. Thebestwaytoillustratethis,Ithink,iswithaquickdemonstration:
1 . 2 . 3 . 4 .
en.wikibooks.org/wiki/Ruby_Programming/Print_version
32/126
10/24/13
displays
P r i n c e s sf r o mA l d e r a a n R e b e lw i t h o u tac a u s e F a r m b o yt u r n e dJ e d i
Icouldhavealsowrittenthislikeso:
IcouldhavebeenmoreverboseaboutdefiningmyhashIcouldhavewrittenitlikethis:
IfIfeltlikeoffingLuke,Icoulddosomethinglikethis:
a s h . 1 .h d e l e t e ( : l u k e )
NowLuke'snolongerinthehash.OrletssayIjusthadavendettaagainstfarmboysingeneral.Icoulddothis:
a s h . k e y ,v a l u e a l u e . . 1 .h d e l e t e _ i f{ | |v d o w n c a s e m a t c h ( " f a r m b o y " ) }
en.wikibooks.org/wiki/Ruby_Programming/Print_version
33/126
10/24/13
a s h 1 .h [ : l a n d o ]=" D a s h i n ga n dd e b o n a i rc i t ya d m i n i s t r a t o r . "
Arrays
A r r a y sarealotlike H a s h es,exceptthatthekeysarealwaysconsecutivenumbers,andalwaysstartsat0.Inan A r r a y withfiveitems,the last elementwould befoundat a r r a y [ 4 ] andthe first elementwouldbefoundat a r r a y [ 0 ] .Inaddition,allthemethodsthatyoujustlearnedwith H a s h escanalsobeappliedto A r r a y s. Herearetwowaystocreatean A r r a y :
r r a y 1=[ ," ," ," ," 1 .a " h e l l o " t h i s " i s " a n " a r r a y ! " ] a r r a y 2 = 2 . [ ] r r a y 2< 3 .a <" T h i s " #i n d e x0 a r r a y 2< 4 . <" i s " #i n d e x1 5 .a r r a y 2< <" a l s o " #i n d e x2 r r a y 2< 6 .a <" a n " #i n d e x3 r r a y 2< 7 .a <" a r r a y ! "#i n d e x4
Asyoumayhaveguessed,the < < operatorpushesvaluesontotheendofan A r r a y .IfIweretowrite p u t sa r r a y 2 [ 4 ] afterdeclaringthosetwo A r r a y sthe outputwouldbe a r r a y ! .Ofcourse,ifIfeltlikesimultaneouslygetting a r r a y ! anddeletingitfromthearray,Icouldjust A r r a y . p o p itoff.The A r r a y . p o p method returnsthe last elementinanarrayandthenimmediatelyremovesitfromthatarray:
r r a y 2 . 1 .s t r i n g=a p o p
en.wikibooks.org/wiki/Ruby_Programming/Print_version
34/126
10/24/13
r r a y 1< r r a y 2 . r r a y 2 . ? 1 .a <a p o pu n t i la e m p t y
Afterthatcodeisevaluated,allofthefollowingaretrue: a r r a y 3 containsalloftheelementsthat a r r a y 1 did,excepttheonesthatwerealsoin a r r a y 2 . Alltheelementsof a r r a y 1 ,minustheelementsof a r r a y 2 ,arenowcontainedwithin a r r a y 3 . a r r a y 4 nowcontainsalltheelementsofboth a r r a y 1 and a r r a y 2 . Youmaysearchforaparticularvalueinvariable a r r a y 1 withthe A r r a y . i n c l u d e ? method: a r r a y 1 . i n c l u d e ? ( " I st h i si nh e r e ? " ) Ifyoujustwantedtoturnthewhole A r r a y intoa S t r i n g ,youcould:
r r a y 2 . 1 .s t r i n g=a j o i n ( "" )
Ifarray2hadthevaluethatwedeclaredinthelastexample,then s t r i n g 'svaluewouldbe
T h i si sa l s oa na r r a y !
Wecouldhavecalledthe A r r a y . j o i n methodwithoutanyarguments:
r r a y 2 . 1 .s t r i n g=a j o i n
s t r i n g 'svaluewouldnowbe
T h i s i s a l s o a n a r r a y !
en.wikibooks.org/wiki/Ruby_Programming/Print_version
35/126
10/24/13
Strings
Iwouldrecommendreadingthechaptersonstringsandalternatequotesnowifyouhaven'talready.Thischapterisgoingtocoversomeprettyspiffythings with S t r i n g sandjustassumethatyoualreadyknowtheinformationinthesetwochapters. InRuby,therearesomeprettycoolbuiltinfunctionswhere S t r i n g sareconcerned.Forexample,youcanmultiplythem:
" D a n g e r ,W i l lR o b i n s o n ! "*5
yields
D a n g e r ,W i l lR o b i n s o n ! D a n g e r ,W i l lR o b i n s o n ! D a n g e r ,W i l lR o b i n s o n ! D a n g e r ,W i l lR o b i n s o n ! D a n g e r ,W i l lR o b i n s o n !
S t r i n g smayalsobecompared:
" a "<" b "
yields
t r u e
TheprecedingevaluationisactuallycomparingtheASCIIvaluesofthecharacters.Butwhat,Ihearyouask,istheASCIIvalueofangivencharacter?With rubyversionspriorto1.9youcanfindtheASCIIvalueofacharacterwith:
A 1 .p u t s?
. 1 .p u t s" A " o r d
Eitherapproachwilldisplay
6 5
en.wikibooks.org/wiki/Ruby_Programming/Print_version 36/126
10/24/13
. 1 .p u t s6 5 c h r
displays
A
yields
H i ,t h i si sac o n c a t e n a t e ds t r i n g !
h i n g 1=" 1 .t R e df i s h ," t h i n g 2=" 2 . b l u ef i s h . " t r i n g 1=t h i n g 1+t h i n g 2+"A 3 .s n ds oo na n ds of o r t h . " s t r i n g 2 = 4 . " # { t h i n g 1+t h i n g 2 }A n ds oo na n ds of o r t h . " 5 .s t r i n g 3=" # { t h i n g 1 } # { t h i n g 2 }A n ds oo na n ds of o r t h . "
h i n g=" 1 .t R e df i s h " h i n g . . l e t t e r e t t e r 2 .t s c a n ( / / ){ | |p u t sl }
en.wikibooks.org/wiki/Ruby_Programming/Print_version
37/126
10/24/13
Displayseachletterin t h i n g (putsautomaticallyaddsanewlineaftereachcall):
R e d f i s h
Butwhat'swiththatweird" / . / "thingintheparameter?That,myfriend,iscalleda regularexpression.They'rehelpfullittlebuggers,quitepowerful,but outsidethescopeofthisdiscussion.Allyouneedtoknowfornowisthat / . / is"regex"speakfor"any onecharacter."Ifwehadused / . . / thenrubywould haveiteratedovereachgroupoftwocharacters,andmissedthelastonesincethere'sanoddnumberofcharacters! Anotheruseforregularexpressionscanbefoundwiththe = ~ operator.Youcanchecktoseeifa S t r i n g matchesaregularexpressionusingthematch operator, = ~ :
displays
Y e a h ,t h e r e ' san u m b e ri nt h i so n e .
en.wikibooks.org/wiki/Ruby_Programming/Print_version
38/126
10/24/13
Now s t r i n g 2 contains 2+2=5 .Butwhatifthe S t r i n g containslotsofliesliketheoneyoujustcorrected? S t r i n g . s u b onlyreplacesthefirstoccurrenceofa word!Iguessyoucoulditeratethroughthe S t r i n g using S t r i n g . m a t c h methodanda w h i l e loop,butthere'samuchmoreefficientwaytoaccomplishthis:
BigBrotherwouldbe soproud! S t r i n g . g s u b isthe" global substitute"function.Everyoccurrenceof" D o w nw i t h "hasnowbeenreplacedwith" L o n gl i v e "sonow w i n s t o n isonlyproclaimingitsloveforBigBrother,notitsdisdainthereof. Onthathappynote,letsmoveonto I n t e g e r sand F l o a t s.Ifyouwanttolearnmoreaboutmethodsinthe S t r i n g class,lookattheendofthischapterfora quickreferencetable.
Numbers(IntegersandFloats)
Youcanskipthisparagraphifyouknowallthestandardnumberoperators.Forthosewhodon't,here'sacrashcourse. + addstwonumberstogether. subtractsthem. / divides. * multiplies. % returnstheremainderoftwodividednumbers. Alright,integersarenumberswithnodecimalplace.Floatsarenumberswithdecimalplaces. 1 0/3 yields 3 becausedividingtwointegersyieldsaninteger. Sinceintegershavenodecimalplacesallyougetis 3 .Ifyoutried 1 0 . 0/3 youwouldget 3 . 3 3 3 3 3 . . . Ifyouhaveevenonefloatinthemixyougetafloatback. Capice? Alright,let'sgetdowntothefunpart.EverythinginRubyisanobject,letmereiterate.Thatmeansthatprettymucheverythinghasatleastonemethod. Integersandfloatsarenoexception.FirstI'llshowyousomeintegermethods. Herewehavethevenerable t i m e s method.Useitwheneveryouwanttodosomethingmorethanonce.Examples:
p u t s" Iw i l ln o wc o u n tt o9 9 . . . " 1 0 0 . t i m e s{ | n u m b e r |p u t sn u m b e r } 5 . t i m e s{ p u t s" G u e s sw h a t ? " } p u t s" I ' md o n e ! "
10/24/13
nutshell.Nowhere'sthatquickreferencetableforstringmethodsIpromisedyou.
AdditionalStringMethods
#O u t p u t s1 5 8 5 7 6 1 5 4 5 " M a r yJ " . h a s h #O u t p u t s" c o n c a t e n a t e " " c o n c a t "+" e n a t e " #O u t p u t s" W a s h i n g t o n " " w a s h i n g t o n " . c a p i t a l i z e #O u t p u t s" u p p e r c a s e " " U P P E R C A S E " . d o w n c a s e #O u t p u t s" L O W E R C A S E " " l o w e r c a s e " . u p c a s e #O u t p u t s" H e n r yV I I " " H e n r yV I I I " . c h o p #O u t p u t s" r o r r i M " " M i r r o r " . r e v e r s e #O u t p u t s8 1 0 " A l lF e a r s " . s u m #O u t p u t sc R a Z y W a T e R s
en.wikibooks.org/wiki/Ruby_Programming/Print_version 40/126
10/24/13
" C r A z Y w A t E r S " . s w a p c a s e #O u t p u t s" N e x u "( n e x ta d v a n c e st h ew o r du po n ev a l u e ,a si fi tw e r ean u m b e r . ) " N e x t " . n e x t #A f t e rt h i s ,n x t= =" N e y n "( t oh e l py o uu n d e r s t a n dt h et r i p p i n e s so fn e x t ) n x t=" N e x t " 2 0 . t i m e s{ n x t=n x t . n e x t }
BasicRubyWritingmethods
DefiningMethods
Methodsaredefinedusingthedefkeywordandendedwiththeendkeyword.SomeprogrammersfindtheMethodsdefinedinRubyverysimilartothosein Python.
d e fm y M e t h o d e n d
Todefineamethodthattakesinavalue,youcanputthelocalvariablenameinparenthesesafterthemethoddefinition.Thevariableusedcanonlybe accessedfrominsidethemethodscope.
d e fm y M e t h o d ( m s g ) p u t sm s g e n d
Ifmultiplevariablesneedtobeusedinthemethod,theycanbeseparatedwithacomma.
d e fm y M e t h o d ( m s g ,p e r s o n ) p u t s" H i ,m yn a m ei s"+p e r s o n+" .S o m ei n f o r m a t i o na b o u tm y s e l f :"+m s g e n d
Anyobjectcanbepassedthroughusingmethods.
d e fm y M e t h o d ( m y O b j e c t ) i f ( m y O b j e c t . i s _ a ? ( I n t e g e r ) ) p u t s" Y o u rO b j e c ti sa nI n t e g e r " e n d # C h e c kt os e ei fi td e f i n e da sa nO b j e c tt h a tw ec r e a t e d # Y o uw i l ll e a r nh o wt od e f i n eO b j e c t si nal a t e rs e c t i o n i f ( m y O b j e c t . i s _ a ? ( M y O b j e c t ) ) p u t s" Y o u rO b j e c ti saM y O b j e c t "
en.wikibooks.org/wiki/Ruby_Programming/Print_version 41/126
10/24/13
e n d e n d
Thereturnkeywordcanbeusedtospecifythatyouwillbereturningavaluefromthemethoddefined.
d e fm y M e t h o d r e t u r n" H e l l o " e n d
Itisalsoworthnotingthatrubywillreturnthelastexpressionevaluated,sothisisfunctionallyequivalenttothepreviousmethod.
d e fm y M e t h o d " H e l l o " e n d
SomeoftheBasicOperatorscanbeoverriddenusingthedefkeywordandtheoperatorthatyouwishtooverride.
d e f= = ( o V a l ) i fo V a l . i s _ a ? ( I n t e g e r ) # @ v a l u ei s av a r i a b l ed e f i n e di nt h ec l a s sw h e r et h i sm e t h o di sd e f i n e d # T h i sw i l lb ec o v e r e di nal a t e rs e c t i o nw h e nd e a l i n gw i t hC l a s s e s i f ( o V a l= =@ v a l u e ) r e t u r nt r u e e l s e r e t u r nf a l s e e n d e n d e n d
BasicRubyClassesandobjects
RubyClasses
Asstatedbefore,everythinginRubyisanobject.Everyobjecthasaclass.Tofindtheclassofanobject,simplycallthatobject's c l a s s method.Forexample, trythis:
p u t s" T h i si sas t r i n g " . c l a s s p u t s9 . c l a s s p u t s[ " t h i s " , " i s " , " a n " , " a r r a y " ] . c l a s s p u t s{ : t h i s= >" i s " ,: a= >" h a s h " } . c l a s s p u t s: s y m b o l . c l a s s
en.wikibooks.org/wiki/Ruby_Programming/Print_version 42/126
10/24/13
Anyhow,youshouldalreadyknowthis.Whatyoudon'tknowhowever,ishowtomakeyourownclassesandextendRuby'sclasses.
CreatingInstancesofaClass
Aninstanceofaclassisanobjectthathasthatclass.Forexample, " c h o c o l a t e " isaninstanceoftheStringclass.Youalreadyknowthatyoucancreatestrings, arrays,hashes,numbers,andotherbuiltintypesbysimplyusingquotes,brackets,curlybraces,etc.,butyoucanalsocreatethemviathe n e w method.For example, m y _ s t r i n g=" " isthesameas m y _ s t r i n g=S t r i n g . n e w .Everyclasshasa n e w method:arrays,hashes,integers,whatever.Whenyoucreateyourown classes,you'llusethe n e w methodtocreateinstances.
CreatingClasses
Classesrepresentatypeofanobject,suchasabook,awhale,agrape,orchocolate.Everybodylikeschocolate,solet'smakeachocolateclass:
c l a s sC h o c o l a t e d e fe a t p u t s" T h a tt a s t e dg r e a t ! " e n d e n d
Tocallthe e a t methodofaninstanceoftheChocolateclass,wewouldusethiscode:
m y _ c h o c o l a t e=C h o c o l a t e . n e w m y _ c h o c o l a t e . e a t#o u t p u t s" T h a tt a s t e dg r e a t ! "
Youcanalsocallamethodbyusing s e n d
" h e l l o " . s e n d ( : l e n g t h )#o u t p u t s" 5 " m y _ c h o c o l a t e . s e n d ( : e a t )#o u t p u t s" T h a tt a s t e dg r e a t ! "
10/24/13
Self
Insideamethodofaclass,thepseudovariable s e l f (apseudovariableisonethatcannotbechanged)referstothecurrentinstance.Forexample:
c l a s sI n t e g e r d e fm o r e r e t u r ns e l f+1 e n d e n d 3 . m o r e#>4 7 . m o r e#>8
ClassMethods
Youcanalsocreatemethodsthatarecalledonaclassratherthananinstance.Forexample:
c l a s sS t r a w b e r r y d e fS t r a w b e r r y . c o l o r r e t u r n" r e d " e n d d e fs e l f . s i z e r e t u r n" k i n d as m a l l " e n d c l a s s< <s e l f d e fs h a p e r e t u r n" s t r a w b e r r y i s h " e n d e n d e n d S t r a w b e r r y . c o l o r#>" r e d " S t r a w b e r r y . s i z e #>" k i n d as m a l l " S t r a w b e r r y . s h a p e#>" s t r a w b e r r y i s h "
Notethethreedifferentconstructions: C l a s s N a m e . m e t h o d _ n a m e and s e l f . m e t h o d _ n a m e areessentiallythesameoutsideofamethoddefinitioninaclassblock, s e l f referstotheclassitself.Thelatterispreferred,asitmakeschangingthenameoftheclassmucheasier.Thelastconstruction, c l a s s< <s e l f ,putsusinthe contextoftheclass's"metaclass"(sometimescalledthe"eigenclass").Themetaclassisaspecialclassthattheclassitselfbelongsto.However,atthispoint, youdon'tneedtoworryaboutit.Allthisconstructdoesisallowustodefinemethodswithoutthe s e l f . prefix.
BasicRubyExceptions
Thereisnoexceptionschapteratpresent.Instead,hereisalinktoachapteraboutexceptionsfrom YukihiroMatsumoto'sbook, ProgrammingRuby:The PragmaticProgrammer'sGuide[1](http://www.rubydoc.org/docs/ProgrammingRuby/html/tut_exceptions.html)Moredetailandsimplerexamplesabout exceptions,by SatishTalim,maybefoundinatutorialatRubyLearning.com[2](http://rubylearning.com/satishtalim/ruby_exceptions.html)
en.wikibooks.org/wiki/Ruby_Programming/Print_version 44/126
10/24/13
SyntaxLexicology
Identifiers
An identifierisanameusedtoidentifyavariable,method,orclass. Aswithmostlanguages,valididentifiersconsistofalphanumericcharacters(A Z a z 0 9 )andunderscores(_ ),butmaynotbeginwithadigit(0 9 ).Additionally, identifiersthatare methodnamesmayendwithaquestionmark(? ),exclamationpoint(! ),orequalssign(= ). Therearenoarbitraryrestrictionstothelengthofanidentifier(i.e.itmaybeaslongasyoulike,limitedonlybyyourcomputer'smemory).Finally,thereare reservedwordswhichmaynotbeusedasidentifiers. Examples:
f o o b a r r u b y _ i s _ s i m p l e
Comments
Linecommentsrunfromabare'#'charactertotheendoftheline.CodecommentinganddocumentationisbestimplementedwithRubyEmbedded Documentation.http://www.rubydoc.org/docs/ProgrammingRuby/html/rdtool.html Examples:
#t h i sl i n ed o e sn o t h i n g ; p r i n t" H e l l o "#t h i sl i n ep r i n t s" H e l l o "
EmbeddedDocumentation
Example:
= b e g i n E v e r y t h i n gb e t w e e nal i n eb e g i n n i n gw i t h` = b e g i n 'd o w nt o o n eb e g i n n i n gw i t h` = e n d 'w i l lb es k i p p e db yt h ei n t e r p r e t e r . T h e s er e s e r v e dw o r d sm u s tb e g i ni nc o l u m n1 . = e n d
ReservedWords
ThefollowingwordsarereservedinRuby:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 45/126
10/24/13
_ _ F I L E _ _ _ _ L I N E _ _ B E G I N E N D a l i a s
a n d b e g i n b r e a k c a s e c l a s s
d e f d e f i n e d ? d o e l s e e l s i f
e n d e n s u r e f a l s e f o r i f
i n m o d u l e n e x t n i l n o t
o r r e d o r e s c u e r e t r y r e t u r n
s e l f s u p e r t h e n t r u e u n d e f
u n l e s s u n t i l w h e n w h i l e y i e l d
Youcanfindsomeexamplesofusingthemhere(http://rubydoc.org/docs/keywords/1.9).
Expressions
Example:
t r u e ( 1+2 )*3 f o o ( ) i ft e s tt h e no k a ye l s en o t _ g o o de n d
TheaboveequivalentinalanguagesuchasCwouldgenerateasyntaxerrorsincecontrolstructuresarenotexpressionsintheClanguage.
SyntaxVariablesandConstants
AvariableinRubycanbedistinguishedbythecharactersatthestartofitsname.There'snorestrictiontothelengthofavariable'sname(withtheexception oftheheapsize).
LocalVariables
Example:
en.wikibooks.org/wiki/Ruby_Programming/Print_version
46/126
10/24/13
f o o b a r
Avariablewhosenamebeginswithalowercaseletter(az)orunderscore(_)isalocalvariableormethodinvocation. Alocalvariableisonlyaccessiblefromwithintheblockofitsinitialization.Forexample:
i 0=1 l o o p{ i 1=2 p u t sd e f i n e d ? ( i 0 ) p u t sd e f i n e d ? ( i 1 ) b r e a k } p u t sd e f i n e d ? ( i 0 ) p u t sd e f i n e d ? ( i 1 )
InstanceVariables
Example:
@ f o o b a r
ClassVariables
Aclassvariableissharedbyallinstancesofaclass.Example:
@ @ f o o b a r
Animportantnoteisthattheclassvariableissharedbyallthedescendantsoftheclass.Example:
c l a s sP a r e n t @ @ f o o=" P a r e n t " e n d c l a s sT h i n g 1<P a r e n t @ @ f o o=" T h i n g 1 " e n d c l a s sT h i n g 2<P a r e n t @ @ f o o=" T h i n g 2 " e n d
en.wikibooks.org/wiki/Ruby_Programming/Print_version 47/126
10/24/13
> > P a r e n t . c l a s s _ e v a l ( " @ @ f o o " ) = > " T h i n g 2 " > > T h i n g 1 . c l a s s _ e v a l ( " @ @ f o o " ) = > " T h i n g 2 " > > T h i n g 2 . c l a s s _ e v a l ( " @ @ f o o " ) = > " T h i n g 2 " > > T h i n g 2 . c l a s s _ v a r i a b l e s = > [ ] P a r e n t . c l a s s _ v a r i a b l e s = > [ : @ @ f o o ]
GlobalVariables
Example:
$ f o o b a r
Avariablewhosenamebeginswith'$ 'hasaglobalscopemeaningitcanbeaccessedfromanywherewithintheprogramduringruntime.
Constants
Usage:
F O O B A R
Howconstantsarelookedup
Constantsarelookedupbasedonyourscope.Forexample
c l a s sA A 2=' a 2 ' c l a s sB
en.wikibooks.org/wiki/Ruby_Programming/Print_version 48/126
10/24/13
d e fg o A 2 e n d e n d e n d i n s t a n c e _ o f _ b=A : : B . n e w a 2=A : : A 2
PseudoVariables
s e l f
Executioncontextofthecurrentmethod.
n i l
Thesoleinstanceofthe N i l C l a s s class.Expressesnothing.
t r u e
Thesoleinstanceofthe T r u e C l a s s class.Expressestrue.
f a l s e
Thesoleinstanceofthe F a l s e C l a s s class.Expressesfalse.
$ 1 ,$ 2. . .$ 9
PredefinedVariables
Name
$ ! $ @ $ & $ `
Aliases
[1] $ E R R O R _ I N F O [1] $ E R R O R _ P O S I T I O N [1] $ M A T C H [1] $ P R E M A T C H
en.wikibooks.org/wiki/Ruby_Programming/Print_version
10/24/13
$ ' $ + $ 1 to $ 9 $ ~ $ =
[1] $ P O S T M A T C H [1] $ L A S T _ P A R E N _ M A T C H
[1] $ L A S T _ M A T C H _ I N F O [1] $ I G N O R E C A S E [1], $ I N P U T _ R E C O R D _ S E P A R A T O R [1]or $ $ R S 0 [1] $ O U T P U T _ R E C O R D _ S E P A R A T O R [1] or $ O R S [1] $ O U T P U T _ F I E L D _ S E P A R A T O R [1] or $ O F S [1], $ [1] $ F I E L D _ S E P A R A T O R F S
$ /
$ \
TheoutputrecordseparatorfortheprintandIO#write.Defaultisnil.
$ ,
TheoutputfieldseparatorfortheprintandArray#join.
$ ;
or $ F
[1]or $ I N P U T _ L I N E _ N U M B E R [1] $ N R [1] $ D E F A U L T _ I N P U T
ThedefaultseparatorforString#split.
$ .
$ < $ F I L E N A M E $ > $ _ $ 0 $ *
[1] $ D E F A U L T _ O U T P U T [1] $ L A S T _ R E A D _ L I N E
$ $
$ ?
[1] $ C H I L D _ S T A T U S
en.wikibooks.org/wiki/Ruby_Programming/Print_version
50/126
10/24/13
$ : $ " $ s t d e r r $ s t d i n $ s t d o u t $ d $ K $ v $ a $ i $ l $ p $ w
$ L O A D _ P A T H $ L O A D E D _ F E A T U R E S or $ I
$ D E B U G $ K C O D E $ V E R B O S E
WithEnglish:
r e q u i r e" E n g l i s h " $ O U T P U T _ F I E L D _ S E P A R A T O R='-' " w a t e r b u f f a l o "= ~/ b u f f / p r i n t$ L O A D E D _ F E A T U R E S ,$ P O S T M A T C H ,$ P I D ," \ n "
PredefinedConstants
en.wikibooks.org/wiki/Ruby_Programming/Print_version 51/126
10/24/13
Notethattherearesomepredefinedconstantsatparsetime,aswell,namely
_ _ F I L E _ _( c u r r e n tf i l e ) _ _ L I N E _ _( c u r r e n tl i n e )
and
_ _ d i r _ _( c u r r e n td i r e c t o r y )
(newinRuby2.0)
Notes
1. a b c d e f g h i j k l m n o p q r s t u v w x y zEnglish.rb(http://rubydoc.org/stdlib/libdoc/English/rdoc/index.html)fromtheRuby1.9.2Standard LibraryDocumentation(http://rubydoc.org/stdlib/)
SyntaxLiterals
Numerics
1 2 3 1 2 3 1 _ 1 2 3 5 4 3 1 2 3 _ 4 5 6 _ 7 8 9 _ 1 2 3 _ 4 5 6 _ 7 8 9 1 2 3 . 4 5 1 . 2 e 3 0 x a a b b 0 3 7 7 0 b 1 0 1 0 0 b 0 0 1 _ 0 0 1 ? a ? \ C a ? \ M a ? \ M \ C a #F i x n u m #F i x n u m( s i g n e d ) #F i x n u m( u n d e r s c o r ei si g n o r e d ) #N e g a t i v eF i x n u m #B i g n u m #F l o a t #F l o a t #( H e x a d e c i m a l )F i x n u m #( O c t a l )F i x n u m #( B i n a r y[ n e g a t e d ] )F i x n u m #( B i n a r y )F i x n u m #A S C I Ic h a r a c t e rc o d ef o r' a '( 9 7 ) #C o n t r o l a( 1 ) #M e t a a( 2 2 5 ) #M e t a C o n t r o l a( 1 2 9 )
Note:themeaningof"?x"notationhasbeenchanged.Inruby1.9thismeansnotanASCIInumericcodebutastringi.e.?a=="a"
Strings
Examples:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 52/126
10/24/13
" t h i si sas t r i n g " = >" t h i si sas t r i n g " " t h r e ep l u st h r e ei s# { 3 + 3 } " = >" t h r e ep l u st h r e ei s6 " f o o b a r=" b l a h " " t h ev a l u eo ff o o b a ri s# { f o o b a r } " = >" t h ev a l u eo ff o o b a ri sb l a h " ' t h ev a l u eo ff o o b a ri s# { f o o b a r } ' = >" t h ev a l u eo ff o o b a ri s\ # { f o o b a r } "
Astringexpressionbeginsandendswithadoubleorsinglequotemark.Doublequotedstringexpressionsaresubjecttobackslashnotationandinterpolation. Asinglequotedstringexpressionisn'texceptfor\'and\\.
BackslashNotation
Alsocalled escapecharactersor escapesequences,theyareusedtoinsertspecialcharactersinastring. Example:
" t h i si sa \ n t w ol i n es t r i n g " " t h i ss t r i n gh a s\ " q u o t e s \ "i ni t "
en.wikibooks.org/wiki/Ruby_Programming/Print_version
53/126
10/24/13
EscapeSequence Meaning \n \s \r \t \v \f \b \a \e \nnn \xnn \unnnn \cx \Cx \Mx \M\Cx \x newline(0x0a) space(0x20) carriagereturn(0x0d) tab(0x09) verticaltab(0x0b) formfeed(0x0c) backspace(0x08) bell/alert(0x07) escape(0x1b) characterwithoctalvaluennn characterwithhexadecimalvaluenn UnicodecodepointU+nnnn(Ruby1.9andlater) controlx controlx metax metacontrolx characterxitself(\"asinglequote,forexample)
Forcharacterswithdecimalvalues,youcandothis:
" "< <1 9 7#a d dd e c i m a lv a l u e3 0 4t oas t r i n g
orembedthemthus:
" # { 1 9 7 . c h r } "
Interpolation
InterpolationallowsRubycodetoappearwithinastring.Theresultofevaluatingthatcodeisinsertedintothestring:
" 1+2=# { 1+2 } " # = >" 1+2=3 "
en.wikibooks.org/wiki/Ruby_Programming/Print_version
54/126
10/24/13
# { e x p r e s s i o n }
TheexpressioncanbejustaboutanyRubycode.Rubyisprettysmartabouthandlingstringdelimitersthatappearinthecodeanditgenerallydoeswhatyou wantittodo.Thecodewillhavethesamesideeffectsasitwouldoutsidethestring,includinganyerrors:
" t h em e a n i n go fl i f ei s# { 1 / 0 } " = >d i v i d e db y0( Z e r o D i v i s i o n E r r o r )
The%Notation
ThereisalsoaPerlinspiredwaytoquotestrings:byusing%(percentcharacter)andspecifyingadelimitingcharacter,forexample:
% { 7 8 %o fs t a t i s t i c sa r e" m a d eu p "o nt h es p o t } = >" 7 8 %o fs t a t i s t i c sa r e\ " m a d eu p \ "o nt h es p o t "
Amodifiercharactercanappearafterthe%,asin%q[],%Q[],%x[]thesedeterminehowthestringisinterpolatedandwhattypeofobjectisproduced: Modifier Meaning %q[] %Q[] %r[] %i[] %I[] %w[] %W[] %x[] NoninterpolatedString(exceptfor\\\[and\]) InterpolatedString(default) InterpolatedRegexp(flagscanappearaftertheclosingdelimiter) NoninterpolatedArrayofsymbols,separatedbywhitespace(afterRuby2.0) InterpolatedArrayofsymbols,separatedbywhitespace(afterRuby2.0) NoninterpolatedArrayofwords,separatedbywhitespace InterpolatedArrayofwords,separatedbywhitespace Interpolatedshellcommand
en.wikibooks.org/wiki/Ruby_Programming/Print_version
55/126
10/24/13
Herearesomemoreexamples:
% Q { o n e \ n t w o \ n # {1+2} } = >" o n e \ n t w o \ n 3 " % q { o n e \ n t w o \ n # {1+2} } = >" o n e \ \ n t w o \ \ n # {1+2} " % r / # { n a m e } / i = >/ n e m o / i % w { o n et w ot h r e e } = >[ " o n e " ," t w o " ," t h r e e " ] % i { o n et w ot h r e e }#a f t e rR u b y2 . 0 = >[ : o n e ,: t w o ,: t h r e e ] % x { r u b yc o p y r i g h t } = >" r u b y-C o p y r i g h t( C )1 9 9 3 2 0 0 9Y u k i h i r oM a t s u m o t o \ n "
"Heredocument"notation
Thereisyetanotherwaytomakeastring,knownasa'heredocument',wherethedelimiteritselfcanbeanystring:
s t r i n g=< < E N D o nt h eo n et o nt e m p l eb e l l am o o n m o t h ,f o l d e di n t os l e e p , s i t ss t i l l . E N D
Thesyntaxbeginswith<<andisfollowedimmediatelybythedelimiter.Toendthestring,thedelimiterappearsaloneonaline. Thereisaslightlynicerwaytowriteaheredocumentwhichallowstheendingdelimitertobeindentedbywhitespace:
s t r i n g=< < F I N o nt h eo n e t o nt e m p l eb e l l am o o n m o t h ,f o l d e di n t os l e e p s i t ss t i l l . T a n i g u c h iB u s o n ,1 8 t hc e n t u r y ;t r a n s l a t e db yX .J .K e n n e d y F I N
Tousenonalphanumericcharactersinthedelimiter,itcanbequoted:
en.wikibooks.org/wiki/Ruby_Programming/Print_version
56/126
10/24/13
Youcaneven"stack"multipleheredocuments:
s t r i n g=[ < < O N E ,< < T W O ,< < T H R E E ] t h ef i r s tt h i n g O N E t h es e c o n dt h i n g T W O a n dt h et h i r dt h i n g T H R E E = >[ " t h ef i r s tt h i n g \ n " ," t h es e c o n dt h i n g \ n " ," a n dt h et h i r dt h i n g \ n " ]
Arrays
Anarrayisacollectionofobjectsindexedbyanonnegativeinteger.Youcancreateanarrayobjectbywriting A r r a y . n e w ,bywritinganoptionalcomma separatedlistofvaluesinsidesquarebrackets,orifthearraywillonlycontainstringobjects,aspacedelimitedstringprecededby % w .
a r r a y _ o n e =A r r a y . n e w a r r a y _ t w o =[ ] #s h o r t h a n df o rA r r a y . n e w a r r a y _ t h r e e=[ " a " ," b " ," c " ]#a r r a y _ t h r e ec o n t a i n s" a " ," b "a n d" c " a r r a y _ f o u r =% w [ abc ] #a r r a y _ f o u ra l s oc o n t a i n s" a " ," b "a n d" c "
a r r a y _ t h r e e [ 0 ] a r r a y _ t h r e e [ 2 ]
en.wikibooks.org/wiki/Ruby_Programming/Print_version
10/24/13
a r r a y _ f o u r [ 0 ] #= >" a " # n e g a t i v ei n d i c e sa r ec o u n t e db a c kf r o mt h ee n d a r r a y _ f o u r [ 2 ] #= >" b " # [ s t a r t ,c o u n t ]i n d e x i n gr e t u r n sa na r r a yo fc o u n to b j e c t sb e g i n n i n ga ti n d e xs t a r t a r r a y _ f o u r [ 1 , 2 ] #= >[ " b " ," c " ] # u s i n gr a n g e s .T h ee n dp o s i t i o ni si n c l u d e dw i t ht w op e r i o d sb u tn o tw i t ht h r e e a r r a y _ f o u r [ 0 . . 1 ] #= >[ " a " ," b " ] a r r a y _ f o u r [ 0 . . . 1 ] #= >[ " a " ]
Hashes
Hashesarebasicallythesameasarrays,exceptthatahashnotonlycontainsvalues,butalsokeyspointingtothosevalues.Eachkeycanoccuronlyonceina hash.Ahashobjectiscreatedbywriting H a s h . n e w orbywritinganoptionallistofcommaseparated k e y= >v a l u e pairsinsidecurlybraces.
h a s h _ o n e =H a s h . n e w h a s h _ t w o ={ } #s h o r t h a n df o rH a s h . n e w h a s h _ t h r e e={ " a "= >1 ," b "= >2 ," c "= >3 }# = >{ " a " = > 1 ," b " = > 2 ," c " = > 3 }
UsuallySymbolsareusedforHashkeys(allowsforquickeraccess),soyouwillseehashesdeclaredlikethis:
h a s h _ s y m ={: a= >1 ,: b= >2 ,: c= >3 } # = >{ : b = > 2 ,: c = > 3 ,: a = > 1 } h a s h _ s y m ={a :1 ,b :2 ,c :3 } # = >{ : b = > 2 ,: c = > 3 ,: a = > 1 }
ThelatterformwasintroducedinRuby1.9.
Hashordering
Notethatwith1.8,iteratingoverhasheswilliterateoverthekeyvaluepairsina"random"order.Beginningwith1.9,itwilliterateoverthemintheorderthey wereinserted.Notehowever,thatifyoureinsertakey(orchangeanexistingkey'svalue),thatdoesnotchangethatkeys'orderintheiteration.
> >a={ : a= >1 ,: b= >2 ,: c= >3 }
en.wikibooks.org/wiki/Ruby_Programming/Print_version 58/126
10/24/13
= >{ : a = > 1 ,: b = > 2 ,: c = > 3 } > >a . k e y s#i t e r a t eo v e r ,s h o wm et h ek e y s = >[ : a ,: b ,: c ] > >a [ : b ]=4 >a . k e y s = >[ : a ,: b ,: c ]#s a m eo r d e r > >a . d e l e t e ( : b ) > >a [ : b ]=4#r ei n s e r tn o w = >4 > >a . k e y s = >[ : a ,: c ,: b ]#d i f f e r e n to r d e r
Ranges
A rangerepresentsasubsetofallpossiblevaluesofatype,tobemoreprecise,allpossiblevaluesbetweenastartvalueandanendvalue. Thismaybe: Allintegersbetween0and5. Allnumbers(includingnonintegers)between0and1,excluding1. Allcharactersbetween't'and'y'. InRuby,theserangesareexpressedby:
0 . . 5 0 . 0 . . . 1 . 0 ' t ' . . ' y '
10/24/13
p u t sr= = =7 #= >f a l s e
FordetailedinformationofallRangemethods,consulttheRangeclassreference. Here(http://www.engineyard.com/blog/2010/iterationshouldntspinyourwheels/)isatutorialontheiruse.
SyntaxOperators
Operators
1.Assignment
AssignmentinRubyisdoneusingtheequaloperator"=".Thisisbothforvariablesandobjects,butsincestrings,floats,andintegersareactuallyobjectsin Ruby,you'realwaysassigningobjects. Examples:
1 . 2 . 3 .
m y v a r=' m y v a ri sn o wt h i ss t r i n g ' v a r=3 2 1 d b c o n n=M y s q l : : n e w , , ( ' l o c a l h o s t ' ' r o o t ' ' p a s s w o r d ' )
Selfassignment
1 . 2 . 3 . 4 . 5 . 6 . 7 .
x=1 x+ =x x=x x+ =4 x* =x x* =x * x/ =x
# = > 1 # = > 2 # = > 0 # = > xw a s0s ox =+4#xi sp o s i t i v e4 # = > 1 6 # = > 1 8 4 4 6 7 4 4 0 7 3 7 0 9 5 5 1 6 1 6#R a i s et ot h ep o w e r # = > 1
AfrequentquestionfromCandC++typesis"Howdoyouincrementavariable?Whereare++andoperators?"InRuby,oneshouldusex+=1andx=1to incrementordecrementavariable.
1 . 2 .
x=' a ' x . ! s u c c
en.wikibooks.org/wiki/Ruby_Programming/Print_version
60/126
10/24/13
Multipleassignments Examples:
1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 1 0 . 1 1 . 1 2 .
v a r 1 ,v a r 2 ,v a r 3=1 ,2 ,3 0 0 0 a r 1 p u t sv # = > v a r 1i sn o w1 0 a r 2 p u t sv # = > v a r 2i sn o w2 0 , v a r 3 . . . e t c m y A r r a y = % w ( J o h nM i c h e lF r a nD o u g )#% w ( )c a nb eu s e da ss y n t a c t i cs u g a rt os i m p l i f ya r r a yc r e a t i o n v a r 1 , v a r 2 , v a r 3 , v a r 4 = m y A r r a y * a r 1 p u t sv # = > J o h n v a r p u t s 4 # = > D o u g n a m e s , s c h o o l = m y A r r a y , ' S t .W h a t e v e r ' n a m e s # = > [ " J o h n " ," M i c h e l " ," F r a n " ," D o u g " ] s c h o o l # = > " S t .W h a t e v e r "
Conditionalassignment
1 . 2 . 3 .
x=f i n d _ s o m e t h i n g ( )# = > n i l x| =" | d e f a u l t " # = > " d e f a u l t ":v a l u eo fxw i l lb er e p l a c e dw i t h" d e f a u l t " ,b u to n l yi fxi sn i lo rf a l s e x| =" | o t h e r " # = > " d e f a u l t ":v a l u eo fxi sn o tr e p l a c e di fi ta l r e a d yi so t h e rt h a nn i lo rf a l s e
Operator||=isashorthandformoftheexpression:
1 . x| |x=" d e f a u l t "
Operator||=canbeshorthandforcodelike:
1 .
x=" e s p o n d _ t o ?: ( s o m ef a l l b a c kv a l u e ) "u n l e s sr xo rx
Insameway&&=operatorworks:
en.wikibooks.org/wiki/Ruby_Programming/Print_version
61/126
10/24/13
1 . 2 . 3 . 4 .
x=g e t _ n o d e ( )# = > n i l x& =x . & n e x t _ n o d e# = >n i l:xw i l lb es e tt ox . n e x t _ n o d e ,b u to n l yi fxi sN O Tn i lo rf a l s e x=g e t _ n o d e ( )# = > S o m eN o d e x& =x . & n e x t _ n o d e# = > N e x tN o d e
Operator&&=isashorthandformoftheexpression:
. 1 . x=x& &x g e t _ n o d e ( )
Scope
InRubythere'salocalscope,aglobalscope,aninstancescope,andaclassscope.
LocalScope
Example:
v a r = 2 4 . t i m e sd o| x | p u t sx = x * v a r e n d # = > 0 , 2 , 4 , 6 p u t sx# = > u n d e f i n e dl o c a lv a r i a b l eo rm e t h o d` x 'f o rm a i n : O b j e c t( N a m e E r r o r )
Thiserrorappearsbecausethisx(toplevel)isnotthex(local)insidethedo..endblockthex(local)isalocalvariabletotheblock,whereaswhentryingtheputs x(toplevel)we'recallingaxvariablethatisinthetoplevelscope,andsincethere'snotone,Rubyprotests.
Globalscope
4 . t i m e sd o| $ g l o b a l | $ g l o b a l = $ g l o b a l * v a r e n d # = > 0 , 2 , 4 , 6l a s ta s s i g n m e n to f$ g l o b a li s6 p u t s$ g l o b a l # = >6
Thisworksbecauseprefixingavariablewithadollarsignmakesthevariableaglobal.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 62/126
10/24/13
Instancescope
Withinmethodsofaclass,youcansharevariablesbyprefixingthemwithan@.
c l a s sA d e fs e t u p @ i n s t v a r=1 e n d d e fg o @ i n s t v a r=@ i n s t v a r * 2 p u t s@ i n s t v a r e n d e n d i n s t a n c e=A . n e w i n s t a n c e . s e t u p i n s t a n c e . g o # = >2 i n s t a n c e . g o # = >4
Classscope
Aclassvariableisonethatislikea"static"variableinJava.Itissharedbyallinstancesofaclass.
c l a s sA @ @ c l a s s v a r=1 d e fg o @ @ c l a s s v a r=@ @ c l a s s v a r * 2 p u t s@ @ c l a s s v a r e n d e n d i n s t a n c e=A . n e w i n s t a n c e . g o # = >2 i n s t a n c e=A . n e w i n s t a n c e . g o # = >4-v a r i a b l ei ss h a r e da c r o s si n s t a n c e s
Here'sademoshowingthevarioustypes:
$ v a r i a b l e c l a s sT e s t d e fi n i t i a l i z e ( a r g 1 = ' k i w i ' ) @ i n s t v a r = a r g 1 @ @ c l a s s v a r = @ i n s t v a r + 't o l dy o us o ! ! '
en.wikibooks.org/wiki/Ruby_Programming/Print_version 63/126
10/24/13
l o c a l v a r = @ i n s t v a r e n d d e fp r i n t _ i n s t v a r p u t s@ i n s t v a r e n d d e fp r i n t _ l o c a l v a r p u t s@ @ c l a s s v a r p u t sl o c a l v a r e n d e n d v a r = T e s t . n e w v a r . p r i n t _ i n s t v a r v a r . p r i n t _ l o c a l v a r
# = > " k i w i " ,i tw o r k sb e c a u s ea@ i n s t a n c e _ v a rc a nb ea c c e s e di n s i d et h ec l a s s # = > u n d e f i n e dl o c a lv a r i a b l eo rm e t h o d' l o c a l v a r 'f o r# < T e s t : 0 x 2 b 3 6 2 0 8@ i n s t v a r = " k i w i " >( N a m e E r r o r ) .
# n e w v a ri sc r e a t e da n di th a s@ @ c l a s s v a rw i t ht h es a m ev a l u ea st h ev a r i n s t a n c eo fT e s t ! ! # = > k i w it o l dy o us o ! !
ClassvariableshavethescopeofparentclassANDchildren,thesevariablescanliveacrossclasses,andcanbeaffectedbythechildrenactions)
c l a s sS u b S u b T e s t<T e s t d e fp r i n t _ c l a s s v a r p u t s@ @ c l a s s v a r e n d d e fm o d i f y _ c l a s s v a r @ @ c l a s s v a r = ' k i w ik i w iw a a a i ! ! ' e n d e n d s u b t e s t = S u b S u b T e s t . n e w s u b t e s t . m o d i f y _ c l a s s v a r # l e t sa d dam e t h o dt h a tm o d i f i e st h ec o n t e n t so f@ @ c l a s s v a ri n S u b S u b T e s t s u b t e s t . p r i n t _ c l a s s v a r
ThisnewchildofTestalsohas@@classvarwiththeoriginalvaluenewvar.print_classvar.Thevalueof@@classvarhasbeenchangedto'kiwikiwiwaaai!!' Thisshowsthat@@classvaris"shared"acrossparentandchildclasses.
Defaultscope
Whenyoudon'tencloseyourcodeinanyscopespecifier,ex:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 64/126
10/24/13
@ a=3 3
itaffectsthedefaultscope,whichisanobjectcalled"main". Forexample,ifyouhadonescriptthatsays
@ a=3 3 r e q u i r e' o t h e r _ s c r i p t . r b '
andother_script.rbsays
p u t s@ a # = >3 3
Theycouldsharevariables. Notehowever,thatthetwoscriptsdon'tsharelocalvariables.
Localscopegotchas
Typicallywhenyouarewithinaclass,youcandoasyou'dlikefordefinitions,like.
c l a s sA a=3 i fa= =3 d e fg o 3 e n d e l s e d e fg o 4 e n d e n d e n d
Andalso,procs"bind"totheirsurroundingscope,like
a=3 b=p r o c{a} b . c a l l#3-i tr e m e m b e r e dw h a taw a s
en.wikibooks.org/wiki/Ruby_Programming/Print_version 65/126
10/24/13
However,the"class"and"def"keywordscausean*entirelynew*scope.
c l a s sA a=3 d e fg o r e t u r na#t h i sw o n ' tw o r k ! e n d e n d
Youcangetaroundthislimitationbyusingdefine_method,whichtakesablockandthuskeepstheouterscope(notethatyoucanuseanyblockyouwant,to, too,buthere'sanexample).
c l a s sA a=3 d e f i n e _ m e t h o d ( : g o ){ a } e n d
Here'susinganarbitraryblock
a=3 P R O C=p r o c{a}#g o t t au s es o m e t h i n gb e s i d e sal o c a l #v a r i a b l eb e c a u s et h a t" c l a s s "m a k e su sl o s es c o p e . c l a s sA d e f i n e _ m e t h o d ( : g o ,& P R O C ) e n d
orhere
c l a s sA e n d a=3 A . c l a s s _ e v a ld o d e f i n e _ m e t h o d ( : g o )d o p u t sa e n d e n d
LogicalAnd
en.wikibooks.org/wiki/Ruby_Programming/Print_version 66/126
10/24/13
Thebinary"and"operatorwillreturnthelogicalconjunctionofitstwooperands.Itisthesameas"&&"butwithalowerprecedence.Example:
a=1 b=2 c=n i l p u t s" y a ya l lm ya r g u m e n t sa r et r u e "i faa n db p u t s" o hn o ,o n eo fm ya r g u m e n ti sf a l s e "i faa n dc
LogicalOr
Thebinary"or"operatorwillreturnthelogicaldisjunctionofitstwooperands.Itisthesameas"||"butwithalowerprecedence.Example:
a=n i l b=" f o o " c=a| |b #ci ss e tt o" f o o "i t ' st h es a m ea ss a y i n gc=( a| |b ) c=ao rb #ci ss e tt on i l i t ' st h es a m ea ss a y i n g( c=a )| |bw h i c hi sn o tw h a ty o uw a n t .
SyntaxControlStructures
ControlStructures
ConditionalBranches
RubycancontroltheexecutionofcodeusingConditionalbranches.AconditionalBranchtakestheresultofatestexpressionandexecutesablockofcode dependingwhetherthetestexpressionistrueorfalse.Ifthetestexpressionevaluatestotheconstant f a l s e or n i l ,thetestisfalseotherwise,itistrue.Note thatthenumber z e r o isconsideredtrue,whereasmanyotherprogramminglanguagesconsideritfalse. Inmanypopularprogramminglanguages,conditionalbranchesarestatements.Theycanaffectwhichcodeisexecuted,buttheydonotresultinvalues themselves.InRuby,however,conditionalbranchesareexpressions.Theyevaluatetovalues,justlikeotherexpressionsdo.An i f expression,forexample, notonlydetermineswhetherasubordinateblockofcodewillexecute,butalsoresultsinavalueitself.Forinstance,thefollowing i f expressionevaluatesto3:
i ft r u e 3 e n d
10/24/13
Youcanalsoputthetestexpressionandcodeblockonthesamelineifyouuse t h e n :
i fa= =4t h e na=7e n d # o r i fa= =4 :a=7e n d # N o t et h a tt h e" : "s y n t a xf o ri fo n el i n eb l o c k sd on o tw o r ka n y m o r ei nr u b y1 . 9 .T e r n a r ys t a t e m e n t ss t i l lw o r k
Thisisequalto:
a=5 a=7i fa= =4 p r i n ta#p r i n t s5s i n c et h ei f b l o c ki s n ' te x e c u t e d
10/24/13
The"oneliners"arehandywhenthecodeexecutedintheblockisonelineonly. ifelsifelseexpression Theelsif(notethatit's e l s i f andnot e l s e i f )andelseblocksgiveyoufurthercontrolofyourscriptsbyprovidingtheoptiontoaccommodateadditionaltests.The e l s i f and e l s e blocksareconsideredonlyifthe i f testisfalse.Youcanhaveanynumberof e l s i f blocksbutonlyone i f andone e l s e block. Syntax:
i fe x p r e s s i o n . . . c o d eb l o c k . . . e l s i fa n o t h e re x p r e s s i o n . . . c o d eb l o c k . . . e l s i fa n o t h e re x p r e s s i o n . . . c o d eb l o c k . . . e l s e . . . c o d eb l o c k . . . e n d
Itisalsoknownastheternaryoperatoranditissuggestedtoonlyusethissyntaxforminortasks,suchasstringformatting,becauseofpoorcodereadability thatmayresult.
i r b ( m a i n ) : 0 3 7 : 0 >t r u e?' t ':' f ' = >" t " i r b ( m a i n ) : 0 3 8 : 0 >f a l s e?' t ':' f ' = >" f "
Thisisveryusefulwhendoingstringconcatenationamongotherthings. Example:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 69/126
10/24/13
Also,thiscanbewrittenas:
r e s u l t=i fc o n d i t i o nt h e ne x p r e s s i o n 1e l s ee x p r e s s i o n 2e n d
Assignmentscanbemadeas:
r e s u l t=( v a l u e 1i fe x p r e s s i o n 1 )| |( v a l u e 2i fe x p r e s s i o n 2 )
Notethat,aswithif,thecomparisonoperatoris==.Theassignmentoperatoris=.ThoughRubywillaccepttheassignmentoperator:
w h e na=5t h e np u t s" # { a }e q u a l s5 " #W A R N I N G !T h i sc o d eC H A N G E St h ev a l u eo fa !
thisisnotwantwewant!Here,wewantthecomparisonoperator. Amoreconcisesyntaxforcaseistoimplythecomparison:
c a s ea w h e n0 . . 4t h e np u t s" # { a }i sl e s st h a n5 " w h e n5t h e np u t s" # { a }e q u a l s5 " w h e n5 . . 1 0t h e np u t s" # { a }i sg r e a t e rt h a n5 " e l s ep u t s" u n e x p e c t e dv a l u e# { a }" #J u s ti nc a s e" a "i sb i g g e rt h a n1 0o rn e g a t i v e . e n d
10/24/13
Note:becausetherangesareexplicitlystated,itisagoodcodingpracticetohandleunexpectedvaluesofa.Thisconcisesyntaxisperhapsmostusefulwhen weknowinadvancewhatvaluestoexpect.Forexample:
a=" a p p l e " c a s ea w h e n" v a n i l l a "t h e n" as p i c e " w h e n " s p i n a c h "t h e n" av e g e t a b l e " w h e n" a p p l e "t h e n" af r u i t " e l s e" a nu n e x p e c t e dv a l u e " e n d
IfenteredintoIRBthisgives:
= >" af r u i t "
OtherwaystousecaseandvariationsonitssyntaxmaybeseenatLinuxtopiaRubyProgramming[3] (http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Expressions_Case_Expressions.html)
Loops
while The w h i l e statementinRubyisverysimilarto i f andtootherlanguages' w h i l e (syntactically):
w h i l e< e x p r e s s i o n > < . . . c o d eb l o c k . . . > e n d
Notethefollowingstrangecaseworks...
l i n e=r e a d l i n e . c h o m pw h i l el i n e! =" w h a tI ' ml o o k i n gf o r "
10/24/13
Keywords
return
r e t u r nv a l u e causesthemethodinwhichitappearstoexitatthatpointandreturnthevaluespecified
Notethatifnoreturnofavalueisspecifiedinamethodthevalueofthelastvaluesetisimplicitlyreturnedasthereturnvalueofthemethod.
SyntaxMethodCalls
A methodinRubyisasetofexpressionsthatreturnsavalue.Withmethods,onecanorganizetheircodeintosubroutinesthatcanbeeasilyinvokedfrom otherareasoftheirprogram.Otherlanguagessometimesrefertothisasafunction.Amethodmaybedefinedasapartofaclassorseparately.
MethodCalls
Methodsarecalledusingthefollowingsyntax:
m e t h o d _ n a m e ( p a r a m e t e r 1 ,p a r a m e t e r 2 , )
Ifthemethodhasnoparameterstheparenthesescanusuallybeomittedasinthefollowing:
m e t h o d _ n a m e
Ifyoudon'thavecodethatneedstousemethodresultimmediately,Rubyallowstospecifyparametersomittingparentheses:
r e s u l t s=m e t h o d _ n a m ep a r a m e t e r 1 ,p a r a m e t e r 2 #c a l l i n gm e t h o d ,n o tu s i n gp a r e n t h e s e s
#Y o un e e dt ou s ep a r e n t h e s e si fy o uw a n tt ow o r kw i t ht h er e s u l ti m m e d i a t e l y . #e . g . ,i fam e t h o dr e t u r n sa na r r a ya n dw ew a n tt or e v e r s ee l e m e n to r d e r : r e s u l t s=m e t h o d _ n a m e ( p a r a m e t e r 1 ,p a r a m e t e r 2 ) . r e v e r s e
en.wikibooks.org/wiki/Ruby_Programming/Print_version
72/126
10/24/13
MethodDefinitions
Methodsaredefinedusingthekeyword d e f followedbythe methodname.Methodparametersarespecifiedbetweenparenthesesfollowingthemethodname. The methodbodyisenclosedbythisdefinitiononthetopandtheword e n d onthebottom.Byconventionmethodnamesthatconsistofmultiplewordshave eachwordseparatedbyanunderscore. Example:
d e fo u t p u t _ s o m e t h i n g ( v a l u e ) p u t sv a l u e e n d
ReturnValues
Methodsreturnthevalueofthelaststatementexecuted.Thefollowingcodereturnsthevalue x + y .
d e fc a l c u l a t e _ v a l u e ( x , y ) x+y e n d
Inthiscase,sixwillhavethevalue6.
DefaultValues
Adefaultparametervaluecanbespecifiedduringmethoddefinitiontoreplacethevalueofaparameterifitisnotpassedintothemethod.
d e fs o m e _ m e t h o d ( v a l u e = ' d e f a u l t ' ,a r r = [ ] ) p u t sv a l u e p u t sa r r . l e n g t h e n d s o m e _ m e t h o d ( ' s o m e t h i n g ' )
Themethodcallabovewilloutput:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 73/126
10/24/13
s o m e t h i n g 0
ThefollowingisasyntaxerrorinRuby1.8
d e ff o o (i=7 ,j)#S y n t a xe r r o ri nR u b y1 . 8 . 7U n e x p e c t e d' ) ' ,e x p e c t i n g' = ' r e t u r ni+j e n d
Theabovecodewillworkin1.9.2andwillbelogicallyequivalenttothesnippetbelow
d e ff o o (j ,i=7 ) r e t u r ni+j e n d
VariableLengthArgumentList,AsteriskOperator
Thelastparameterofamethodmaybeprecededbyanasterisk(*),whichissometimescalledthe'splat'operator.Thisindicatesthatmoreparametersmaybe passedtothefunction.Thoseparametersarecollectedupandanarrayiscreated.
d e fc a l c u l a t e _ v a l u e ( x , y , * o t h e r V a l u e s ) p u t so t h e r V a l u e s e n d c a l c u l a t e _ v a l u e ( 1 , 2 , ' a ' , ' b ' , ' c ' )
hasthesameresultas:
c a l c u l a t e _ v a l u e ( ' a ' , ' b ' , ' c ' )
AnothertechniquethatRubyallowsistogiveaHashwheninvokingafunction,andthatgivesyoubestofallworlds:namedparameters,andvariable argumentlength.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 74/126
10/24/13
d e fa c c e p t s _ h a s h (v a r) p r i n t" g o t :" ,v a r . i n s p e c t#w i l lp r i n to u tw h a ti tr e c e i v e d e n d a c c e p t s _ h a s h: a r g 1= >' g i v i n ga r g 1 ' ,: a r g N= >' g i v i n ga r g N ' #= >g o t :{ : a r g N = > " g i v i n ga r g N " ,: a r g 1 = > " g i v i n ga r g 1 " }
Now,ifyouaregoingtopassacodeblocktofunction,youneedparentheses.
a c c e p t s _ h a s h (: a r g 1= >' g i v i n ga r g 1 ' ,: a r g N= >' g i v i n ga r g N ') {| s |p u t ss} a c c e p t s _ h a s h ({: a r g 1= >' g i v i n ga r g 1 ' ,: a r g N= >' g i v i n ga r g N '}) {| s |p u t ss} #s e c o n dl i n ei sm o r ev e r b o s e ,h a s he x p l i c i t l yc r e a t e d ,b u te s s e n t i a l l yt h es a m ea sa b o v e
TheAmpersandOperator
Muchliketheasterisk,theampersand(&)mayprecedethelastparameterofafunctiondeclaration.Thisindicatesthatthefunctionexpectsacodeblocktobe passedin.AProcobjectwillbecreatedandassignedtotheparametercontainingtheblockpassedin. Alsosimilartotheampersandoperator,aProcobjectprecededbyanampersandduringamethodcallwillbereplacedbytheblockthatitcontains. Y i e l d may thenbeused.
d e fm e t h o d _ c a l l y i e l d e n d m e t h o d _ c a l l ( & s o m e B l o c k )
Understandingblocks,Procsandmethods
Introduction Rubyprovidestheprogrammerwithasetofverypowerfulfeaturesborrowedfromthedomainoffunctionalprogramming,namelyclosures,higherorder functions,andfirstclassfunctions[1].ThesefeaturesareimplementedinRubybymeansofcodeblocks,Procobjects,andmethods(thatarealsoobjects) conceptsthatarecloselyrelatedandyetdifferinsubtleways.Infact,Ifoundmyselfquiteconfusedaboutthistopic,havingdifficultyunderstandingthe
en.wikibooks.org/wiki/Ruby_Programming/Print_version 75/126
10/24/13
differencebetweenblocks,procs,andmethodsaswellasunsureaboutthebestpracticesofusingthem.Additionally,havingsomebackgroundinLispand yearsofPerlexperience,IwasunsureofhowtheRubyconceptsmaptosimilaridiomsfromotherprogramminglanguageslikeLispsfunctionsandPerls subroutines.Siftingthroughhundredsofnewsgroupposts,IsawthatIamnottheonlyonewiththisproblemand,infact,quitealotofRubyNubiesstruggle withthesameideas. InthisarticleIlayoutmyunderstandingofthisfacetofRuby,whichcomesasaresultofextensiveresearchofRubybooks,documentation,and comp.lang.ruby,insincerehopethatotherpeoplewillfinditusefulaswell. Procs ShamelesslyrippingfromtheRubydocumentation,Procsaredefinedasfollows:Procobjectsareblocksofcodethathavebeenboundtoasetoflocal variables.Oncebound,thecodemaybecalledindifferentcontextsandstillaccessthosevariables. Ausefulexampleisalsoprovided:
d e fg e n _ t i m e s ( f a c t o r ) r e t u r nP r o c . n e w{ | n |n * f a c t o r} e n d t i m e s 3=g e n _ t i m e s ( 3 ) t i m e s 5=g e n _ t i m e s ( 5 ) #' f a c t o r 'i sr e p l a c e dw i t h3
10/24/13
Actually,therearetwoslightdifferencesbetweenlambdaandProc.new.First,argumentchecking.TheRubydocumentationforlambdastates:Equivalentto Proc.new,excepttheresultingProcobjectscheckthenumberofparameterspassedwhencalled.Hereisanexampletodemonstratethis:
p n e w=P r o c . n e w{ | x ,y |p u t sx+y } l a m b=l a m b d a{ | x ,y |p u t sx+y } #w o r k sf i n e ,p r i n t i n g6 p n e w . c a l l ( 2 ,4 ,1 1 ) #t h r o w sa nA r g u m e n t E r r o r l a m b . c a l l ( 2 ,4 ,1 1 )
Second,thereisadifferenceinthewayreturnsarehandledfromtheProc.AreturnfromProc.newreturnsfromtheenclosingmethod(actingjustlikeareturn fromablock,moreonthislater):
d e ft r y _ r e t _ p r o c n e w r e t=P r o c . n e w{r e t u r n" B a a a m "} r e t . c a l l " T h i si sn o tr e a c h e d " e n d #p r i n t s" B a a a m " p u t st r y _ r e t _ p r o c n e w
Whilereturnfromlambdaactsmoreconventionally,returningtoitscaller:
d e ft r y _ r e t _ l a m b d a r e t=l a m b d a{r e t u r n" B a a a m "} r e t . c a l l " T h i si sp r i n t e d " e n d #p r i n t s" T h i si sp r i n t e d " p u t st r y _ r e t _ l a m b d a
10/24/13
Simplyput,amethodisalsoablockofcode.However,unlikeProcs,methodsarenotboundtothelocalvariablesaroundthem.Rather,theyareboundto someobjectandhaveaccesstoitsinstancevariables[3]:
c l a s sB o o g y d e fi n i t i a l i z e @ d i x=1 5 e n d d e fa r b o p u t s" # { @ d i x }h a \ n " e n d e n d #i n i t i a l i z e sa ni n s t a n c eo fB o o g y b=B o o g y . n e w #p r i n t s" 1 5h a " b . a r b o
Notethatmethodscanalsobedefinedinthesocalledtoplevelscope,whichisnotinsideanyuserdefinedclass.Forexample:
d e fs a y( s o m e t h i n g ) p u t ss o m e t h i n g e n d s a y" H e l l o "
Whileitseemsthatthemethod sayisfreestanding,itisnotRubysilentlytucksitintotheObjectclass,whichrepresentsthescopeofyourapplication:
d e fs a y( s o m e t h i n g ) p u t ss o m e t h i n g
en.wikibooks.org/wiki/Ruby_Programming/Print_version 78/126
10/24/13
en.wikibooks.org/wiki/Ruby_Programming/Print_version
79/126
10/24/13
1 0 . t i m e sd o| i | p r i n t" # { i }" e n d n u m b e r s=[ 1 ,2 ,5 ,6 ,9 ,2 1 ] n u m b e r s . e a c hd o| x | p u t s" # { x }i s"+( x> =3?" m a n y ":" f e w " ) e n d s q u a r e s=n u m b e r s . m a p{ | x |x*x }
Themethoddo_twiceisdefinedandcalledwithanattachedblock.Althoughthemethoddidnotexplicitlyaskfortheblockinitsargumentslist,theyieldcan calltheblock.ThiscanbeimplementedinamoreexplicitwayusingaProcargument:
d e fd o _ t w i c e ( w h a t ) w h a t . c a l l w h a t . c a l l e n d d o _ t w i c el a m b d a{ p u t s" H o l a " }
Thisisequivalenttothepreviousexamplebutusingblockswithyieldiscleanerandbetteroptimizedsinceonlyoneblockispassedtothemethod.Usingthe Procapproach,anyamountofcodeblockscanbepassed:
d e fd o _ t w i c e ( w h a t 1 ,w h a t 2 ,w h a t 3 ) 2 . t i m e sd o w h a t 1 . c a l l w h a t 2 . c a l l w h a t 3 . c a l l
en.wikibooks.org/wiki/Ruby_Programming/Print_version 80/126
10/24/13
10/24/13
Dynamicmethods
Youcandefineamethodon"justoneobject"inRuby.
a=' b '
en.wikibooks.org/wiki/Ruby_Programming/Print_version 82/126
10/24/13
Oryoucanusedefine_(singleton_)method,whichpreservesthescopearoundthedefinition,aswell.
a=' b ' a . d e f i n e _ s i n g l e t o n _ m e t h o d ( : s o m e _ m e t h o d ){ ' w i t h i nab l o c km e t h o d ' } a . s o m e _ m e t h o d
Specialmethods
Rubyhasanumberofspecialmethodsthatarecalledbytheinterpreter.Forexample:
c l a s sC h a m e l e o n a l i a s_ _ i n s p e c t _ _i n s p e c t d e fm e t h o d _ m i s s i n g ( m e t h o d ,* a r g ) i f( m e t h o d . t o _ s ) [ 0 . . 2 ]= =" t o _ " @ i d e n t i t y=_ _ i n s p e c t _ _ . s u b ( " C h a m e l e o n " ,m e t h o d . t o _ s . s u b ( ' t o _ ' , ' ' ) . c a p i t a l i z e ) d e fi n s p e c t @ i d e n t i t y e n d s e l f e l s e s u p e r# m e t h o d _ m i s s i n go v e r r i d e st h ed e f a u l tK e r n e l . m e t h o d _ m i s s i n g # p a s so na n y t h i n gw ew e r e n ' tl o o k i n gf o rs ot h eC h a m e l e o ns t a y su n n o t i c e da n du n e a t e n; ) e n d e n d e n d m r l i z a r d=C h a m e l e o n . n e w m r l i z a r d . t o _ r o c k
Conclusion
Rubydoesntreallyhavefunctions.Rather,ithastwoslightlydifferentconceptsmethodsandProcs(whichare,aswehaveseen,simplywhatother languagescallfunctionobjects,orfunctors).BothareblocksofcodemethodsareboundtoObjects,andProcsareboundtothelocalvariablesinscope. Theirusesarequitedifferent.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 83/126
10/24/13
Methodsarethecornerstoneofobjectorientedprogramming,andsinceRubyisapureOOlanguage(everythingisanobject),methodsareinherenttothe natureofRuby.MethodsaretheactionsRubyobjectsdothemessagestheyreceive,ifyoupreferthemessagesendingidiom. Procsmakepowerfulfunctionalprogrammingparadigmspossible,turningcodeintoafirstclassobjectofRubyallowingtoimplementhighorderfunctions. TheyareveryclosekintoLispslambdaforms(thereslittledoubtabouttheoriginofRubysProcconstructorlambda) Theconstructofablockmayatfirstbeconfusing,butitturnsouttobequitesimple.Ablockis,asmymetaphorgoes,anunbornProcitisaProcinan intermediatestate,notboundtoanythingyet.IthinkthatthesimplestwaytothinkaboutblocksinRuby,withoutlosinganycomprehension,wouldbetothink thatblocksarereallyaformofProcs,andnotaseparateconcept.TheonlytimewhenwehavetothinkofblocksasslightlydifferentfromProcsisthespecial casewhentheyarepassedasthelastargumenttoamethodwhichmaythenaccessthemusingyield. Thatsaboutit,Iguess.IknowforsurethattheresearchIconductedforthisarticleclearedmanymisunderstandingsIhadabouttheconceptspresentedhere. Ihopeotherswilllearnfromitaswell.Ifyouseeanythingyoudontagreewithfromglaringerrorstosmallinaccuracies,feelfreetoamendthebook. Notes [1]Itseemsthatinthepure,theoreticalinterpretationwhatRubyhasisntfirstclassfunctionsperse.However,asthisarticledemonstrates,Rubyisperfectly capableoffulfillingmostoftherequirementsforfirstclassfunctions,namelythatfunctionscanbecreatedduringtheexecutionofaprogram,storedindata structures,passedasargumentstootherfunctions,andreturnedasthevaluesofotherfunctions. [2]lambdahasasynonymproc,whichisconsideredmildlydeprecated(mainlybecauseprocandProc.newareslightlydifferent,whichisconfusing).Inother words,justuselambda. [3]Theseareinstancemethods.Rubyalsosupportsclassmethods,andclassvariables,butthatisnotwhatthisarticleisabout. [4]Ormoreaccurately,calland[]bothrefertothesamemethodofclassProc.Yes,Procobjectsthemselveshavemethods!
SyntaxClasses
Classesarethebasictemplatefromwhichobjectinstancesarecreated.Aclassismadeupofacollectionofvariablesrepresentinginternalstateand methodsprovidingbehavioursthatoperateonthatstate.
ClassDefinition
ClassesaredefinedinRubyusingthe c l a s s keywordfollowedbyaname.Thenamemustbeginwithacapitalletterandbyconventionnamesthatcontain morethanonewordareruntogetherwitheachwordcapitalizedandnoseparatingcharacters(CamelCase).Theclassdefinitionmaycontainmethod,class variable,andinstancevariabledeclarationsaswellascallstomethodsthatexecuteintheclasscontextatreadtime,suchasattr_accessor.Theclass declarationisterminatedbythe e n d keyword. Example:
c l a s sM y C l a s s d e fs o m e _ m e t h o d e n d
en.wikibooks.org/wiki/Ruby_Programming/Print_version 84/126
10/24/13
e n d
InstanceVariables
Instancevariablesarecreatedforeachclassinstanceandareaccessibleonlywithinthatinstance.Theyareaccessedusingthe@operator.Outsideofthe classdefinition,thevalueofaninstancevariablecanonlybereadormodifiedviathatinstance'spublicmethods. Example:
c l a s sM y C l a s s @ o n e=1 d e fd o _ s o m e t h i n g @ o n e=2 e n d d e fo u t p u t p u t s@ o n e e n d e n d i n s t a n c e=M y C l a s s . n e w i n s t a n c e . o u t p u t i n s t a n c e . d o _ s o m e t h i n g i n s t a n c e . o u t p u t
Surprisingly,thisoutputs:
n i l 2
AccessorMethods
Asnotedintheprevioussection,aninstancevariablecanonlybedirectlyaccessedormodifiedwithinaninstancemethoddefinition.Ifyouwanttoprovide accesstoitfromoutside,youneedtodefinepublicaccessormethods,forexample
c l a s sM y C l a s s d e fi n i t i a l i z e @ f o o=2 8 e n d d e ff o o r e t u r n@ f o o
en.wikibooks.org/wiki/Ruby_Programming/Print_version 85/126
10/24/13
Notethatrubyprovidesabitofsyntacticsugartomakeitlooklikeyouaregettingandsettingavariabledirectlyunderthehood
a=i n s t a n c e . f o o i n s t a n c e . f o o=b
arecallstothefooandfoo=methods
a=i n s t a n c e . f o o ( ) i n s t a n c e . f o o = ( b )
Sincethisissuchacommonusecase,thereisalsoaconveniencemethodtoautogeneratethesegettersandsetters:
c l a s sM y C l a s s a t t r _ a c c e s s o r: f o o d e fi n i t i a l i z e @ f o o=2 8 e n d e n d i n s t a n c e=M y C l a s s . n e w p u t si n s t a n c e . f o o i n s t a n c e . f o o=4 9 6 p u t si n s t a n c e . f o o
10/24/13
ClassVariables
Classvariablesareaccessedusingthe@@operator.Thesevariablesareassociatedwiththeclasshierarchyratherthananyobjectinstanceoftheclassand arethesameacrossallobjectinstances.(Thesearesimilartoclass"static"variablesinJavaorC++). Example:
c l a s sM y C l a s s @ @ v a l u e=1 d e fa d d _ o n e @ @ v a l u e =@ @ v a l u e+1 e n d d e fv a l u e @ @ v a l u e e n d e n d i n s t a n c e O n e=M y C l a s s . n e w i n s t a n c e T w o=M y C l a s s . n e w p u t si n s t a n c e O n e . v a l u e i n s t a n c e O n e . a d d _ o n e p u t si n s t a n c e O n e . v a l u e p u t si n s t a n c e T w o . v a l u e
Outputs:
1 2 2
ClassInstanceVariables
en.wikibooks.org/wiki/Ruby_Programming/Print_version 87/126
10/24/13
Classescanhaveinstancevariables.Thisgiveseachclassavariablethatisnotsharedbyotherclassesintheinheritancechain.
c l a s sE m p l o y e e c l a s s< <s e l f ;a t t r _ a c c e s s o r: i n s t a n c e s ;e n d d e fs t o r e s e l f . c l a s s . i n s t a n c e s| | =[ ] s e l f . c l a s s . i n s t a n c e s< <s e l f e n d d e fi n i t i a l i z en a m e @ n a m e=n a m e e n d e n d c l a s sO v e r h e a d<E m p l o y e e ;e n d c l a s sP r o g r a m m e r<E m p l o y e e ;e n d O v e r h e a d . n e w ( ' M a r t i n ' ) . s t o r e O v e r h e a d . n e w ( ' R o y ' ) . s t o r e P r o g r a m m e r . n e w ( ' E r i k ' ) . s t o r e p u t sO v e r h e a d . i n s t a n c e s . s i z e #= >2 p u t sP r o g r a m m e r . i n s t a n c e s . s i z e #= >1
Formoredetails,seeMFBliki:ClassInstanceVariables(http://martinfowler.com/bliki/ClassInstanceVariable.html)
ClassMethods
Classmethodsaredeclaredthesamewayasnormalmethods,exceptthattheyareprefixedby s e l f ,ortheclassname,followedbyaperiod.Thesemethods areexecutedattheClasslevelandmaybecalledwithoutanobjectinstance.Theycannotaccessinstancevariablesbutdohaveaccesstoclassvariables. Example:
c l a s sM y C l a s s d e fs e l f . s o m e _ m e t h o d p u t s' s o m e t h i n g ' e n d e n d M y C l a s s . s o m e _ m e t h o d
Outputs:
s o m e t h i n g
Instantiation
Anobjectinstanceiscreatedfromaclassthroughtheaprocesscalled instantiation.InRubythistakesplacethroughtheClassmethod n e w . Example:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 88/126
10/24/13
a n O b j e c t=M y C l a s s . n e w ( p a r a m e t e r s )
DeclaringVisibility
Bydefault,allmethodsinRubyclassesarepublicaccessiblebyanyone.Thereare,nonetheless,onlytwoexceptionsforthisrule:theglobalmethods definedundertheObjectclass,andtheinitializemethodforanyclass.Bothofthemareimplicitlyprivate. Ifdesired,theaccessformethodscanberestrictedbypublic,private,protectedobjectmethods. Itisinterestingthatthesearenotactuallykeywords,butactualmethodsthatoperateontheclass,dynamicallyalteringthevisibilityofthemethods,andasa result,these'keywords'influencethevisibilityofallfollowingdeclarationsuntilanewvisibilityissetortheendofthedeclarationbodyisreached.
Private
Simpleexample:
c l a s sE x a m p l e d e fm e t h o d A e n d p r i v a t e#a l lm e t h o d st h a tf o l l o ww i l lb em a d ep r i v a t e :n o ta c c e s s i b l ef o ro u t s i d eo b j e c t s d e fm e t h o d P e n d e n d
Ifprivateisinvokedwithoutarguments,itsetsaccesstoprivateforallsubsequentmethods.Itcanalsobeinvokedwithnamedarguments. Namedprivatemethodexample:
c l a s sE x a m p l e d e fm e t h o d A e n d d e fm e t h o d P e n d
en.wikibooks.org/wiki/Ruby_Programming/Print_version 89/126
10/24/13
p r i v a t e: m e t h o d P e n d
Note:anotherpopularwaytocodethesamedeclaration
c l a s sS i n g l e t o n L i k e p r i v a t e _ c l a s s _ m e t h o d: n e w d e fS i n g l e t o n L i k e . c r e a t e ( * a r g s ,& b l o c k ) @ @ i n s t| | =n e w ( * a r g s ,& b l o c k ) e n d e n d
10/24/13
e n d e n d
Here,"other_object"isthe"receiver"thatmethod"a"isinvokedon.Forprivatemethods,itdoesnotwork.However,thatiswhat"protected"visibilitywill allow.
Public
Publicisdefaultaccessibilitylevelforclassmethods.Iamnotsurewhythisisspecifiedmaybeforcompleteness,maybesothatyoucoulddynamicallymake somemethodprivateatsomepoint,andlaterpublic. InRuby,visibilityiscompletelydynamic.Youcanchangemethodvisibilityatruntime!
Protected
Now,protecteddeservesmorediscussion.ThoseofyoucomingfromJavaorC++havelearnedthatinthoselanguages,ifamethodisprivate,itsvisibility isrestrictedtothedeclaringclass,andifthemethodisprotected,itwillbeaccessibletochildrenoftheclass(classesthatinheritfromparent)orother classesinthatpackage. InRuby,privatevisibilityissimilartowhatprotectedisinJava.PrivatemethodsinRubyareaccessiblefromchildren.Youcanthavetrulyprivatemethods inRubyyoucantcompletelyhideamethod. Thedifferencebetweenprotectedandprivateissubtle.Ifamethodisprotected,itmaybecalledbyanyinstanceofthedefiningclassoritssubclasses.Ifa methodisprivate,itmaybecalledonlywithinthecontextofthecallingobjectitisneverpossibletoaccessanotherobjectinstance'sprivatemethodsdirectly, eveniftheobjectisofthesameclassasthecaller.Forprotectedmethods,theyareaccessiblefromobjectsofthesameclass(orchildren). So,fromwithinanobject"a1"(aninstanceofClassA),youcancallprivatemethodsonlyforinstanceof"a1"(self).Andyoucannotcallprivatemethodsof object"a2"(thatalsoisofclassA)theyareprivatetoa2.Butyoucancallprotectedmethodsofobject"a2"sinceobjectsa1anda2arebothofclassA. RubyFAQ(http://www.rubycentral.com/faq/rubyfaq7.html)givesfollowingexampleimplementinganoperatorthatcomparesoneinternalvariablewitha variablefromthesameclass(forpurposesofcomparingtheobjects):
d e f< = > ( o t h e r ) s e l f . a g e< = >o t h e r . a g e e n d
InstanceVariables
en.wikibooks.org/wiki/Ruby_Programming/Print_version 91/126
10/24/13
Notethatobjectinstancevariablesarenotreallyprivate,youjustcan'tseethem.Toaccessaninstancevariable,youneedtocreateagetterandsetter. Likethis(no,don'tdothisbyhand!Seebelow):
c l a s sG o t A c c e s s o r d e fi n i t i a l i z e ( s i z e ) @ s i z e=s i z e e n d d e fs i z e @ s i z e e n d d e fs i z e = ( v a l ) @ s i z e=v a l e n d e n d #y o uc o u l dt h ea c c e s s@ s i z ev a r i a b l ea s #a=G o t A c c e s s o r . n e w ( 5 ) #x=a . s i z e #a . s i z e=y
Inheritance
Aclasscan inherit functionalityandvariablesfroma superclass,sometimesreferredtoasa parentclassor baseclass.Rubydoesnotsupport multiple inheritanceandsoaclassinRubycanhaveonlyonesuperclass.Thesyntaxisasfollows:
en.wikibooks.org/wiki/Ruby_Programming/Print_version
92/126
10/24/13
Outputs:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 93/126
10/24/13
a b
Allnonprivatevariablesandfunctionsareinheritedbythechildclassfromthesuperclass. Ifyourclassoverridesamethodfromparentclass(superclass),youstillcanaccesstheparent'smethodbyusing'super'keyword.
c l a s sP a r e n t C l a s s d e fa _ m e t h o d p u t s' b ' e n d e n d c l a s sS o m e C l a s s<P a r e n t C l a s s d e fa _ m e t h o d s u p e r p u t s' a ' e n d e n d i n s t a n c e=S o m e C l a s s . n e w i n s t a n c e . a _ m e t h o d
Outputs:
b a
en.wikibooks.org/wiki/Ruby_Programming/Print_version
94/126
10/24/13
Outputs
h e l l o h e l l o y h e l l o z
MixinginModules
First,youneedtoreaduponmodulesRubymodules(http://www.rubydoc.org/docs/ProgrammingRuby/html/tut_modules.html).Modulesareawayof groupingtogethersomefunctionsandvariablesandclasses,somewhatlikeclasses,butmorelikenamespaces.Soamoduleisnotreallyaclass.Youcan't instantiateaModule,andthusitdoesnothave self . Thistrait,however,allowsustoincludethemoduleintoaclass.Mixitin,sotospeak.
m o d u l eA d e fa 1 p u t s' a 1i sc a l l e d ' e n d e n d m o d u l eB d e fb 1 p u t s' b 1i sc a l l e d ' e n d e n d m o d u l eC d e fc 1 p u t s' c 1i sc a l l e d ' e n d e n d c l a s sT e s t i n c l u d eA i n c l u d eB i n c l u d eC d e fd i s p l a y p u t s' M o d u l e sa r ei n c l u d e d '
en.wikibooks.org/wiki/Ruby_Programming/Print_version 95/126
10/24/13
e n d e n d o b j e c t = T e s t . n e w o b j e c t . d i s p l a y o b j e c t . a 1 o b j e c t . b 1 o b j e c t . c 1
Outputs:
M o d u l e sa r ei n c l u d e d a 1i sc a l l e d b 1i sc a l l e d c 1i sc a l l e d
ThecodeshowsMultipleInheritanceusingmodules.
RubyClassMetaModel
InkeepingwiththeRubyprinciplethateverythingisanobject,classesarethemselvesinstancesoftheclassClass.Theyarestoredinconstantsunderthe scopeofthemoduleinwhichtheyaredeclared.Acalltoamethodonanobjectinstanceisdelegatedtoavariableinsidetheobjectthatcontainsareference totheclassofthatobject.ThemethodimplementationexistsontheClassinstanceobjectitself.Classmethodsareimplementedonmetaclassesthatare linkedtotheexistingclassinstanceobjectsinthesamewaythatthoseclassesinstancesarelinkedtothem.ThesemetaclassesarehiddenfrommostRuby functions.
SyntaxHooks
Rubyprovidescallbacks,to,forexample,knowwhenanewmethodisdefined(later)inaclass. Here(http://www.nachvorne.de/2007/3/18/listofcallbackmethods/)isalistofknowncallbacks.
const_missing
c l a s sO b j e c t d e fs e l f . c o n s t _ m i s s i n gc p' m i s s i n gc o n s tw a s ' ,c e n d e n d
ormore
c l a s sO b j e c t
en.wikibooks.org/wiki/Ruby_Programming/Print_version 96/126
10/24/13
Seealsosomerdoc(http://rubydoc.org/docs/keywords/1.9/)documentationonthevariouskeywords.
References BuiltInFunctions
Bydefaultmanymethodsareavailable.Youcanseetheavailableonesbyrunning m e t h o d s inanirbsession,ex:
> >c l a s sA ;e n d > >A . s i n g l e t o n _ m e t h o d s
[ : n i l ? ,: = = = ,: = ~ ,: ! ~ ,: e q l ? ,: c l a s s ,: c l o n e ,: d u p ,: t a i n t ,: t a i n t e d ? ,: u n t a i n t ,: u n t r u s t ,: u n t r u s t e d ? ,: t r u s t ,: f r e e z e ,: f r o z e n ? ,: t o _ s ,: i n s p e c t ,: m e t h o d s ,: s i n g l e t o n _ m e t h o d s ,: p r o t e c t e d _ m
Youcanseewheremostofthosemethodsaredefinedbyinspectingtheobjecthierarchy:
> >A . a n c e s t o r s = >[ A ,O b j e c t ,K e r n e l ,B a s i c O b j e c t ]
PredefinedVariables
Ruby'spredefined(builtin)variablesaffectthebehavioroftheentireprogram,sotheiruseinlibrariesisn'trecommended. Thevaluesinmostpredefinedvariablescanbeaccessedbyalternativemeans.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 97/126
10/24/13
$ !
Thelastexceptionobjectraised.Theexceptionobjectcanalsobeaccessedusing=>inrescueclause.
$ @
Thestackbacktraceforthelastexceptionraised.ThestackbacktraceinformationcanretrievedbyException#backtracemethodofthelastexception.
$ /
Theinputrecordseparator(newlinebydefault).gets,readline,etc.,taketheirinputrecordseparatorasoptionalargument.
$ \
Theoutputrecordseparator(nilbydefault).
$ ,
TheoutputseparatorbetweentheargumentstoprintandArray#join(nilbydefault).YoucanspecifyseparatorexplicitlytoArray#join.
$ ;
Thedefaultseparatorforsplit(nilbydefault).YoucanspecifyseparatorexplicitlyforString#split.
$ .
Thenumberofthelastlinereadfromthecurrentinputfile.EquivalenttoARGF.lineno.
$ <
SynonymforARGF.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 98/126
10/24/13
$ >
Synonymfor$defout.
$ 0
ThenameofthecurrentRubyprogrambeingexecuted.
$ $
Theprocess.pidofthecurrentRubyprogrambeingexecuted.
$ ?
Theexitstatusofthelastprocessterminated.
$ :
Synonymfor$LOAD_PATH.
$ D E B U G
Trueifthedordebugcommandlineoptionisspecified.
$ d e f o u t
Thedestinationoutputforprintandprintf($stdoutbydefault).
$ F
en.wikibooks.org/wiki/Ruby_Programming/Print_version
99/126
10/24/13
Thevariablethatreceivestheoutputfromsplitwhenaisspecified.Thisvariableissetiftheacommandlineoptionisspecifiedalongwiththeporn option.
$ F I L E N A M E
ThenameofthefilecurrentlybeingreadfromARGF.EquivalenttoARGF.filename.
$ L O A D _ P A T H
Anarrayholdingthedirectoriestobesearchedwhenloadingfileswiththeloadandrequiremethods.
$ S A F E
Thesecuritylevel.
0 N oc h e c k sa r ep e r f o r m e do ne x t e r n a l l ys u p p l i e d( t a i n t e d )d a t a .( d e f a u l t ) 1 P o t e n t i a l l yd a n g e r o u so p e r a t i o n su s i n gt a i n t e dd a t aa r ef o r b i d d e n . 2 P o t e n t i a l l yd a n g e r o u so p e r a t i o n so np r o c e s s e sa n df i l e sa r ef o r b i d d e n . 3 A l ln e w l yc r e a t e do b j e c t sa r ec o n s i d e r e dt a i n t e d . 4 M o d i f i c a t i o no fg l o b a ld a t ai sf o r b i d d e n .
$ s t d i n
Standardinput(STDINbydefault).
$ s t d o u t
Standardoutput(STDOUTbydefault).
$ s t d e r r
en.wikibooks.org/wiki/Ruby_Programming/Print_version
100/126
10/24/13
Standarderror(STDERRbydefault).
$ V E R B O S E
Trueifthev,w,orverbosecommandlineoptionisspecified.
$ -x
Thevalueofinterpreteroptionx(x=0,a,d,F,i,K,l,p,v).
Thefollowingarelocalvariables:
$ _
Thelaststringreadbygetsorreadlineinthecurrentscope.
$ ~
MatchDatarelatingtothelastmatch.Regex#matchmethodreturnsthelastmatchinformation.
Thefollowingvariablesholdvaluesthatchangeinaccordancewiththecurrentvalueof$~andcan'treceiveassignment:
$n( $ 1 ,$ 2 ,$ 3 . . . )
Thestringmatchedinthenthgroupofthelastpatternmatch.Equivalenttom[n],wheremisaMatchDataobject.
$ &
Thestringmatchedinthelastpatternmatch.Equivalenttom[0],wheremisaMatchDataobject.
$ `
en.wikibooks.org/wiki/Ruby_Programming/Print_version 101/126
10/24/13
Thestringprecedingthematchinthelastpatternmatch.Equivalenttom.pre_match,wheremisaMatchDataobject.
$ '
Thestringfollowingthematchinthelastpatternmatch.Equivalenttom.post_match,wheremisaMatchDataobject.
$ +
Thestringcorrespondingtothelastsuccessfullymatchedgroupinthelastpatternmatch.
PredefinedClasses
Inrubyeventhe basetypes(also predefinedclasses)canbehacked. [4]Inthefollowingexample, 5 isanimmediate, [5]aliteral,anobject,andaninstance of F i x n u m .
c l a s sF i x n u m a l i a so t h e r _ st o _ s d e ft o _ s ( ) a=s e l f+5 r e t u r na . o t h e r _ s e n d e n d a=5 p u t sa . c l a s s p u t sa p u t s0 p u t s5 p u t s1 0+0 b=5 + 5 p u t sb
Footnotes
1. ^Whichmeansthe4VALUEbytesarenotareferencebutthevalueitself.All 5 havethesameobjectid(whichcouldalsobeachievedinotherways). 2. ^Mightnotalwaysworkasyouwouldlike,thebasetypesdon'thaveaconstructor(d e fi n i t i a l i z e ),andcan'thavesimpletonmethods.Therearesome
en.wikibooks.org/wiki/Ruby_Programming/Print_version 102/126
10/24/13
otherminorexceptions.
Objects
ObjectisthebaseclassofallotherclassescreatedinRuby.Itprovidesthebasicsetoffunctionsavailabletoallclasses,andeachfunctioncanbeexplicitly overriddenbytheuser. ThisclassprovidesanumberofusefulmethodsforalloftheclassesinRuby.
Array
ClassMethods
M e t h o d :[] S i g n a t u r e :A r r a y [[ a n O b j e c t ] *]>a n A r r a y
Createsanewarraywhoseelementsaregivenbetween[and].
A r r a y . [ ] (1 ,2 ,3)>[ 1 , 2 , 3 ] A r r a y [1 ,2 ,3]>[ 1 , 2 , 3 ] [ 1 , 2 , 3 ]>[ 1 , 2 , 3 ]
Class
RubyProgramming/Reference/Objects/Class
Comparable
RubyProgramming/Reference/Objects/Comparable
Encoding
EncodingisbasicallyanewconceptintroducedinRuby1.9 Stringsnowhave"somebytes"and"someencoding"associatedwiththem. In1.8,allstringswerejust"somebytes"(sobasicallytreatedaswhatBINARY/ASCII8BITencodingisin1.9).Youhadtousehelperlibrariestouseany m18nstylestuff. Bydefault,whenyouopenafileandreadfromit,itwillreadasstringswithanencodingsetto
E n c o d i n g . d e f a u l t _ e x t e r n a l (whichyoucanchange).
en.wikibooks.org/wiki/Ruby_Programming/Print_version 103/126
10/24/13
Externallinks
here(http://archive.is/20121220012936/http://blog.grayproductions.net/articles/ruby_19s_three_default_encodings)isonegoodtutorial.here (http://yehudakatz.com/2010/05/17/encodingsunabridged/)isanother.[6](http://github.com/candlerb/string19/blob/master/string19.rb)isanother.
Enumerable
Enumerable
EnumeratorappearsinRubyasEnumerable::Enumeratorin1.8.xand(just)Enumeratorin1.9.x.
FormsofEnumerator
ThereareseveraldifferentwaysinwhichanEnumeratorcanbeused: Asaproxyforeach Asasourceofvaluesfromablock Asanexternaliterator
1.Asaproxyforeach
ThisisthefirstwayofusingEnumerator,introducedinruby1.8.Itsolvesthefollowingproblem:Enumerablemethodslike#mapand#selectcall#eachon yourobject,butwhatifyouwanttoiterateusingsomeothermethodsuchas#each_byteor#each_with_index? AnEnumeratorisasimpleproxyobjectwhichtakesacallto#eachandredirectsittoadifferentmethodontheunderlyingobject.
r e q u i r e' e n u m e r a t o r ' #n e e d e di nr u b y< =1 . 8 . 6o n l y s r c=" h e l l o " p u t ss r c . e n u m _ f o r ( : e a c h _ b y t e ) . m a p{| b |" % 0 2 x "%b} . j o i n ( "" )
Thecalltoenum_for(orequivalentlyto_enum)createstheEnumeratorproxy.Itisashorthandforthefollowing:
n e w s r c=E n u m e r a b l e : : E n u m e r a t o r . n e w ( s r c ,: e a c h _ b y t e )
en.wikibooks.org/wiki/Ruby_Programming/Print_version 104/126
10/24/13
Inruby1.9, E n u m e r a b l e : : E n u m e r a t o r haschangedtojust E n u m e r a t o r
2.Asasourceofvaluesfromablock
Inruby1.9,Enumerator.newcaninsteadtakeablockwhichisexecutedwhen#eachiscalled,anddirectlyyieldsthevalues.
b l o c k= E n u m e r a t o r . n e w{ | g |g . y i e l d1 ;g . y i e l d2 ;g . y i e l d3 } b l o c k . e a c hd o| i t e m | p u t si t e m e n d
Howeveritalsolaysthegroundworkforlazyevaluationofenumerables,describedlater.
3.Asanexternaliterator
ruby1.9alsoallowsyouturnanEnumeratoraroundsothatitbecomesapullsourceofvalues,sometimesknownasexternaliteration.Lookcarefullyatthe differencebetweenthisandthepreviousexample:
b l o c k= E n u m e r a t o r . n e w{ | g |g . y i e l d1 ;g . y i e l d2 ;g . y i e l d3 } w h i l ei t e m=b l o c k . n e x t p u t si t e m e n d
en.wikibooks.org/wiki/Ruby_Programming/Print_version
105/126
10/24/13
Lazyevaluation
InanEnumeratorwithablock,thetargetbeingyieldedtoispassedasanexplicitparameter.Thismakesitpossibletosetupachainofmethodcallssothat eachvalueispassedlefttorightalongthewholechain,ratherthanbuildingupintermediatearraysofvaluesateachstep. ThebasicpatternisanEnumeratorwithablockwhichprocessesinputvaluesandyields(zeroormore)outputvaluesforeachone.
E n u m e r a t o r . n e wd o| y | s o u r c e . e a c hd o| i n p u t | . . . y . y i e l do u t p u t e n d e n d
#f i l t e rI N P U T #f i l t e rO U T P U T
Soletswrapthisinaconveniencemethod:
c l a s sE n u m e r a t o r d e fd e f e r ( & b l k ) s e l f . c l a s s . n e wd o| y | e a c hd o| * i n p u t | b l k . c a l l ( y ,* i n p u t ) e n d e n d e n d e n d
Thisnewmethoddefercanbeusedasalazyformofbothselectandmap.Ratherthanbuildinganarrayofvaluesandreturningthatarrayattheend,it immediatelyyieldseachvalue.Thismeansyoustartgettingtheanswerssooner,anditwillworkwithhugeoreveninfinitelists.Example:
en.wikibooks.org/wiki/Ruby_Programming/Print_version 106/126
10/24/13
MethodswhichreturnEnumerators
From1.8.7on,manyEnumerablemethodswillreturnanEnumeratorifnotgivenablock.
> >a=[ " f o o " , " b a r " , " b a z " ] = >[ " f o o " ," b a r " ," b a z " ] > >b=a . e a c h _ w i t h _ i n d e x = ># < E n u m e r a b l e : : E n u m e r a t o r : 0 x b 7 d 7 c a d c > > >b . e a c h{| a r g s |pa r g s} [ " f o o " ,0 ] [ " b a r " ,1 ] [ " b a z " ,2 ] = >[ " f o o " ," b a r " ," b a z " ] > >
Thismeansthatusuallyyoudontneedtocall e n u m _ f o r explicitly.Theveryfirstexampleonthispagereducestojust:
s r c=" h e l l o " p u t ss r c . e a c h _ b y t e . m a p{| b |" % 0 2 x "%b} . j o i n ( "" )
Thiscanleadtosomewhatoddbehaviourfornonmaplikemethodswhenyoucall#eachontheobjectlater,youhavetoprovideitwiththerightsortof block.
= >[ " f o o " ," b a r " ," b a z " ] > >b=a . s e l e c t = ># < E n u m e r a b l e : : E n u m e r a t o r : 0 x b 7 d 6 c f b 0 > > >b . e a c h{| a r g |a r g<" c "} = >[ " b a r " ," b a z " ] > >
en.wikibooks.org/wiki/Ruby_Programming/Print_version
107/126
10/24/13
MoreEnumeratorreadings
ticket707(http://redmine.rubylang.org/issues/show/707) enum_for(http://www.strictlyuntyped.com/2008/09/ruby187senumeratorclass.html)inStrictlyUntypedblog Generator(http://anthonylewis.com/2007/11/09/rubygenerators/)inAnthonyLewisblog
each_with_index
each_with_indexcallsitsblockwiththeitemanditsindex.
a r r a y=[ ' S u p e r m a n ' , ' B a t m a n ' , ' T h eH u l k ' ] a r r a y . e a c h _ w i t h _ i n d e xd o| i t e m , i n d e x | p u t s" # { i n d e x }># { i t e m } " e n d #w i l lp r i n t #0>S u p e r m a n #1>B a t m a n #2>T h eH u l k
find_all
find_allreturnsonlythoseitemsforwhichthecalledblockisnotfalse
r a n g e=1. .1 0 #f i n dt h ee v e nn u m b e r s a r r a y=r a n g e . f i n d _ a l l{| i t e m |i t e m%2= =0} #r e t u r n s[ 2 , 4 , 6 , 8 , 1 0 ]
a r r a y=[ ' S u p e r m a n ' , ' B a t m a n ' , ' C a t w o m a n ' , ' W o n d e rW o m a n ' ] a r r a y=a r r a y . f i n d _ a l l{| i t e m |i t e m= ~/ w o m a n /} #r e t u r n s[ ' C a t w o m a n ' , ' W o n d e rW o m a n ' ]
Exception
en.wikibooks.org/wiki/Ruby_Programming/Print_version 108/126
10/24/13
Exceptionisthesuperclassforexceptions InstanceMethods
b a c k t r a c e
Returnsthebacktraceinformation(fromwhereexceptionoccurred)asanarrayofstrings.
e x c e p t i o n
Returnsacloneoftheexceptionobject.Thismethodisusedbyraisemethod.
m e s s a g e
Returnstheexceptionmessage.
FalseClass
TheonlyinstanceofFalseClassisfalse. Methods:
f a l s e&o t h e r-L o g i c a lA N D ,w i t h o u ts h o r tc i r c u i tb e h a v i o r f a l s e|o t h e r-L o g i c a lO R ,w i t h o u ts h o r tc i r c u i tb e h a v i o r f a l s e^o t h e r-E x c l u s i v eO r( X O R )
IOFiber
AFiberisaunitofconcurrency(basicallyamanuallycontrolledthread).Itisanewconstructin1.9 1.8basicallyusedgreenthreadssimilar,tofibers,butwouldpreemptthem,which1.9doesnotdo. Seeitsdescription(http://rubydoc.org/core1.9/classes/Fiber.html). Severalusefulthingshavebeenbuiltusingfibers,likeneverblock(http://oldmoe.blogspot.com/2008/07/untwistingeventloop.html),therevactorgem,etal.
IO
TheIOclassisbasicallyanabstractclassthatprovidesmethodstouseonstreams(forexample,openfiles,oropensockets). Basically,youcancallseveraldifferentthingsonit.
en.wikibooks.org/wiki/Ruby_Programming/Print_version 109/126
10/24/13
Encoding
Notethatwith1.9,eachcallwillreturnyouaStringwithanencodingset,basedoneitherhowtheconnectionwasestablished,ex:
a=F i l e . n e w ( ' s o m ef i l e n a m e ' ,' r b : A S C I I 8 B I T ' )#s t r i n g sf r o mt h i sw i l lb er e a di na sA S C I I 8 B I T b=F i l e . n e w ( ' s o m ef i l e n a m e ' ,' r ' )#s t r i n g sf r o mt h i sw i l lb er e a di na sw h a t e v e rt h eE n c o d i n g . d e f a u l t _ e x t e r n a li s #y o uc a nc h a n g ew h a tt h ee n c o d i n gw i l lb e a . s e t _ e n c o d i n g" U T F 8 "#f r o mn o wo ni tw i l lr e a di nU T F 8
gets
g e t s readsexactlyoneline,oruptotheendofthefile/stream(andincludesthetrailingnewline,ifonewasgiven).Ablockingcall.
recv
r e c v ( 1 0 2 4 ) readsuptoatmost1024bytesandreturnsyourtheString.Ablockingcall.Reads""ifasockethasbeenclosedgracefullyfromtheotherend.It
alsohasnonblockingcompanions.
read
r e a d readsuptotheendofthefileoruptothewhenthesocketisclosed.Returnsanynumberofbytes.Blocking.Forinformationonhowtoavoidblocking,
seeSocket.
IOFile File
Thefileclassistypicallyusedforopeningandclosingfiles,aswellasafewmethodslikedeletingthemandstat'ingthem. Ifyouwanttomanipulateafile,notopenit,alsocheckoutthePathnameclass,aswellastheFileUtilsclass. Tocreateadirectoryyou'llneedtousetheDir.mkdirmethod.
File#chmod
Here'showtodotheequivalentof"chmodu+xfilename"
F i l e . c l a s s _ e v a ld o d e fs e l f . a d d m o d ( f l a g s ,f i l e n a m e ) t h e m o d e = s t a t ( f i l e n a m e ) . m o d e|f l a g s c h m o d ( t h e m o d e ,f i l e n a m e )
en.wikibooks.org/wiki/Ruby_Programming/Print_version 110/126
10/24/13
e n d e n d
Althoughthere'snoerrorcheckingandthereturnvaluecouldprobablybesomethingbetter(likethemode). Soafterdefiningthat,your'u+w'wouldbe:@File.addmod(0200,'filename')@fromhttp://www.rubyforum.com/topic/196999#new
File#grep
ThisisactuallyEnumerable#grep,andIbelieveitjustworkspiecewise,like F i l e . e a c h _ l i n e { | l | y i e l dli fl = ~/ w h a t e v e r /}
File.join
Thisisusefulforcombiningobjectsthataren't(ormightnotbe)stringsintoapath.Seehere(http://www.rubyforum.com/topic/206959#new).
IOFile::Stat File::Stat
AFile::Statobjectisonethatcontainsafile'sstatusinformation. Example:
s t a t=F i l e . s t a t ( ' / e t c ' )#aF i l e : : S t a to b j e c t i fs t a t . d i r e c t o r y ? p u t s' / e t ci sad i r e c t o r yl a s tm o d i f i e da t'+s t a t . m t i m e . t o _ s e n d
Youcanalsogetastatobjectforopenfiledescriptors.
a=F i l e . o p e n ( ' s o m ef i l e ' ) a . s t a t#F i l e : : S t a to b j e c t
IOGC GC
RubydoesautomaticGarbageCollection.
en.wikibooks.org/wiki/Ruby_Programming/Print_version
111/126
10/24/13
TuningtheGC
MRI'sGCisa"fullmarkandsweep"andisrunwheneveritrunsoutofmemoryslots(i.e.beforeaddingmorememory,itwillsweeptheexistingtoseeifitcan freeupsomefirstifnotitaddsmorememory).ItalsoistriggeredafterGC_MALLOC_LIMITofbyteshasbeenallocatedbyextensions.Unfortunatelythis causesatraversalofallmemory,whichistypicallyslow.Seeagooddescription(http://timetobleed.com/garbagecollectionandtherubyheapfromrailsconf/). TheGCisknowntotypicallytake10%ofcpu,butifyouhavealargeRAMload,itcouldtakemuchmore. GCcanbetunedat"compiletime"(MRI/KRI's<1.9)http://blog.evanweaver.com/articles/2009/04/09/rubygctuningorcanbetunedbyusingenvironment variables(REE,MRI/KRI's>=1.9). Sometips: YoucansetthecompilervariableGC_MALLOC_LIMITtobeaveryhighvalue,whichcausesyourprogramtousemoreRAMbuttotraverseitmuchless frequently.Goodforlargeapps,likerails. Youcanusejruby/rubiniuswhichusemoresophisticatedGC's. Youcanuse"native"librarieswhichstorethevaluesawaysothatRubydoesn'thavetokeeptrackofthemandcollectthem.Examples:"NArray"gemand "google_hash"gem. Toturnitoff:@GC.disable@ Toforceittorunonce:@GC.start@
Conservative
Ruby's(MRI's)GCismarkandsweep,whichmeansitisconservative.Toaccomplishthis,ittraversesthestack,lookingforanysectionofmemorywhich "looks"likeareferencetoanexistingrubyobject,andmarksthemaslive.Thiscanleadtofalsepositives,evenwhentherearenoreferencestoanobject remaining. Thisproblemisespeciallybadinthe1.8.xseries,whentheydon'thavetheMBARIpatchesapplied(mostdon't,REEdoes).Thisisbecause,whenyouuse threads,itactuallyallocatesafullcopyofthestacktoeachthread,andasthethreadsarerun,theirstackiscopiedtothe"real"stack,andtheycanpickup ghostreferencesthatbelongtootherthreads,andalsobecausethe1.8MRIinterpretercontainshugeswitchstatements,whichleavealotofmemoryonthe stackuntouched,soitcancontinuetocontainreferencesto"ghost"referencesinerror. ThisallmeansthatifyoucallaGC.start,it'snot*guaranteed*tocollectanything. Somehintsaroundthis: Ifyoucallyourcodefromwithinamethod,andcome*out*ofthatmethod,itmightcollectitmorereadily. YoucandosomethingofyourownGCbyusinganensureblock,like
a=S o m e C l a s s . n e w b e g i n
en.wikibooks.org/wiki/Ruby_Programming/Print_version 112/126
10/24/13
. . . e n s u r e a . c l e a n u p e n d
Ifyouwritea"wholelotmore"memoryitmightclearthestackofitsoldreferences.
TunningJruby'sGC.
"here":http://blade.nagaokaut.ac.jp/cgibin/scat.rb/ruby/rubycore/27550isanexampleofhowtotuneJruby'sGC.TheG1GCistheoreticallya"neverpause" GC,thoughinrealitymostofthemareprettygoodatbeingspeedy.Forlongrunningappsyou'llprobablywanttoruninservermode(server),forincreased performance,thoughdecreasedstartuptime. RubiniusisalsosaidtohaveabetterGC.
Howtoavoidperformancepenalty
SinceMRI'sGCisbasicallyO(N)asitgrows,yougetaperformancepenaltywhenGC'soccurandyouareusingalotofRAMinyourapp(andMRIalmost nevergivesitsRAMbacktothesystem).Workarounds: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. uselessRAMbyallocatingfewerobjects doworkinaforked"childprocess"whichreturnsbackthevaluesdesired.Thechildwilldie,freeingupitsmemory. useJrubyetal(jrubyhasanexcellentGCwhichdoesn'tslowthingsdownmuch,evenwithlargerapps). useagemthatallowsfornativetypes,likeNArrayortheRubyGoogleHash. useREEinsteadof1.8.6(sinceitincorporatestheMBARIpatcheswhichmaketheGCmuchmoreefficient). use1.9.xinsteadof1.8.6(sinceitusestruethreadsthereismuchlessreferenceghostingonthestack,thusmakingtheGCmoreefficient). setyourapptorestartperiodically(passengercandothis). createmultipleapps,onedesignedtobelargeandslow,theothersnimble(runyourGCintensiveallinthelargeone). callGC.startyourself,ormixitwithGC.disable usememprofgemtoseewheretheleaksareoccurring(orthedikegemorthelike).
IOGCProfiler
Thisisaclassin1.9MRI
G C : : P r o f i l e r . e n a b l e #. . .s t u f f G C : : P r o f i l e r . r e p o r t#o u t p u t st os t d o u t #o r r e p o r t=G C : : P r o f i l e r . r e s u l t#ai ss e tt oav e r b o s ea s c i is t r i n g G C : : P r o f i l e r . d i s a b l e#s t o pi t
en.wikibooks.org/wiki/Ruby_Programming/Print_version 113/126
10/24/13
Notethattheoutputs"invokeTime(sec)"isactuallythesumofusercputimeuntilthatinvokeoccurredi.e.asleep1willresultititincreasingby0,butabusy loopforonesecondwillresultinitincreasingby1.
Marshal Marshal
TheMarshalclassisusedforserializinganddeserializingobjectstodisk: ex
s e r i a l i z e d=M a r s h a l . d u m p ( [ ' a n ' ,' a r r a y ' ,' o f ' ,' s t r i n g s ' ] ) u n s e r i a l i z e d=M a r s h a l . r e s t o r e ( s e r i a l i z e d )
With1.9,eachdumpalsoincludesanencoding,soyou*must*useMarshal'sstreamreadfeatureifyouwishtoreaditfromanIOobject,likeafile.
a=F i l e . o p e n ( " s e r i a l i z e d _ d a t a " ," w " ) a . w r i t eM a r s h a l . d u m p ( 3 3 ) b=F i l e . o p e n ( " s e r i a l i z e d _ d a t a " ," r " ) u n s e r i a l i z e d=M a r s h a l . r e s t o r e ( b ) b . c l o s e
Method
RubyProgramming/Reference/Objects/Method
Math
RubyProgramming/Reference/Objects/Math
Module
RubyProgramming/Reference/Objects/Module
en.wikibooks.org/wiki/Ruby_Programming/Print_version 114/126
10/24/13
ModuleClass
RubyProgramming/Reference/Objects/Module/Class
NilClass
RubyProgramming/Reference/Objects/NilClass
Numeric
Numericprovidescommonbehaviorofnumbers.Numericisanabstractclass,soitshouldnotbeinstantiated. IncludedModules:
C o m p a r a b l e
InstanceMethods: +n
R e t u r n sn .
n
R e t u r n snn e g a t e d .
n%num
R e t u r n st h em o d u l u so fn .
n**num
en.wikibooks.org/wiki/Ruby_Programming/Print_version
115/126
10/24/13
E x p o n e n t i a t i o n .
n.abs
R e t u r n st h ea b s o l u t ev a l u eo fn .
n.ceil
R e t u r n st h es m a l l e s ti n t e g e rg r e a t e rt h a no re q u a lt on .
n.floor Returnsthelargestintegerlessthanorequalton.
1 . 2 . f l o o r 2 . 1 . f l o o r ( 1 . 2 ) . f l o o r ( 2 . 1 ) . f l o o r # = >1 # = >2 # = >2 # = >3
n.integer?
R e t u r n st r u ei fni sa ni n t e g e r .
n.modulo(num)
R e t u r n st h em o d u l u so b t a i n e db yd i v i d i n gnb yn u ma n dr o u n d i n gt h eq u o t i e n tw i t hf l o o r .E q u i v a l e n tt on . d i v m o d ( n u m ) [ 1 ] .
n.nonzero?
en.wikibooks.org/wiki/Ruby_Programming/Print_version 116/126
10/24/13
R e t u r n sni fi ti s n ' tz e r o ,o t h e r w i s en i l .
n.remainder(num) Returnstheremainderobtainedbydividingnbynumandremovingdecimalsfromthequotient.Theresultandnalwayshavesamesign.
( 1 3 . m o d u l o ( 4 ) ) ( 1 3 . m o d u l o ( 4 ) ) ( ( 1 3 ) . m o d u l o ( 4 ) ) ( ( 1 3 ) . m o d u l o ( 4 ) ) ( 1 3 . r e m a i n d e r ( 4 ) ) ( 1 3 . r e m a i n d e r ( 4 ) ) ( ( 1 3 ) . r e m a i n d e r ( 4 ) ) ( 1 3 ) . r e m a i n d e r ( 4 ) ) # = > 1 # = >3 # = > 3 # = >1 # = > 1 # = > 1 # = >1 # = >1
n.round
R e t u r n snr o u n d e dt ot h en e a r e s ti n t e g e r .
1 . 2 . r o u n d 2 . 5 . r o u n d ( 1 . 2 ) . r o u n d ( 2 . 5 ) . r o u n d
n.truncate
R e t u r n sna sa ni n t e g e rw i t hd e c i m a l sr e m o v e d .
1 . 2 . t r u n c a t e 2 . 1 . t r u n c a t e ( 1 . 2 ) . t r u n c a t e ( 2 . 1 ) . t r u n c a t e
n.zero?
R e t u r n sz e r oi fni s0 .
NumericInteger
en.wikibooks.org/wiki/Ruby_Programming/Print_version 117/126
10/24/13
InstanceMethods: Bitwiseoperations:AND,OR,XOR,andinversion.
~ i i&i n t i|i n t i^i n t i< <i n t i> >i n t
B i t w i s el e f ts h i f ta n dr i g h ts h i f t .
i [ n ]
R e t u r n st h ev a l u eo ft h en t hb i tf r o mt h el e a s ts i g n i f i c a n tb i t ,w h i c hi si [ 0 ] .
5 [ 0 ] 5 [ 1 ] 5 [ 2 ]
i . c h r
R e t u r n sas t r i n gc o n t a i n i n gt h ec h a r a c t e rf o rt h ec h a r a c t e rc o d ei .
6 5 . c h r ? a . c h r
i . d o w n t o (m i n ){ |i |. . . }
en.wikibooks.org/wiki/Ruby_Programming/Print_version 118/126
10/24/13
I n v o k e st h eb l o c k ,d e c r e m e n t i n ge a c ht i m ef r o mit om i n .
3 . d o w n t o ( 1 ){ | i | p u t si }
#p r i n t s : # 3 # 2 # 1
i . n e x t i . s u c c
R e t u r n st h en e x ti n t e g e rf o l l o w i n gi .E q u i v a l e n tt oi+1 .
i . s i z e
R e t u r n st h en u m b e ro fb y t e si nt h em a c h i n er e p r e s e n t a t i o no fi .
i . s t e p (u p t o ,s t e p ){ |i |. . . }
I t e r a t e st h eb l o c kf r o mit ou p t o ,i n c r e m e n t i n gb ys t e pe a c ht i m e .
1 0 . s t e p ( 5 ,2 ){ | i | p u t si } #p r i n t s : # 1 0 # 8 # 6
i . s u c c
S e ei . n e x t
i . t i m e s{ |i |. . . }
en.wikibooks.org/wiki/Ruby_Programming/Print_version 119/126
10/24/13
I t e r a t e st h eb l o c kit i m e s .
3 . t i m e s{ | i | p u t si } #p r i n t s : # 0 # 1 # 2
i . t o _ f
C o n v e r t sii n t oaf l o a t i n gp o i n tn u m b e r .F l o a tc o n v e r s i o nm a yl o s ep r e c i s i o ni n f o r m a t i o n .
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 . t o _ f #= >1 . 2 3 4 5 6 7 8 9 1 e + 1 5
i . t o _ i n t
R e t u r n sii t s e l f .E v e r yo b j e c tt h a th a st o _ i n tm e t h o di st r e a t e da si fi t ' sa ni n t e g e r .
i . u p t o (m a x ){ |i |. . . }
I n v o k e st h eb l o c k ,i n c r e m e n t i n ge a c ht i m ef r o mit om a x .
1 . u p t o ( 3 ){ | i | p u t si } #p r i n t s : # 1 # 2 # 3
NumericIntegerBignum
RubyProgramming/Reference/Objects/Numeric/Integer/Bignum
NumericIntegerFixnum
en.wikibooks.org/wiki/Ruby_Programming/Print_version 120/126
10/24/13
RubyProgramming/Reference/Objects/Numeric/Integer/Fixnum
NumericFloat
RubyProgramming/Reference/Objects/Numeric/Float
Range
RubyProgramming/Reference/Objects/Range
Regexp RegexpRegularExpressions
ClassRegexpholdsaregularexpression,usedtomatchapatternofstrings. Regularexpressionscanbecreatedusing/your_regex_here/orbyusingtheconstructor"new".
> >/ ar e g e x / > >/ ac a s ei n s e n s i t i v er e g e x / i
orusethenewconstructorwithconstants,like
> >R e g e x p . n e w ( ' ar e g e x ' ) > >R e g e x p . n e w ( ' ar e g e x ' ,M U L T I L I N E )
Toseeallavailablecreationoptions,pleaseseetheregexrdoc(http://rubydoc.org/core/classes/Regexp.html).
oniguruma
Startingwith1.9,rubyhasanewRegularExpressionengine(oniguruma),whichisslightlyfasterandmorepowerful,aswellasencodingaware/friendly.To seeagoodexplanationofhowitworks,pleaseseeitsrdoc(http://github.com/ruby/ruby/blob/trunk/doc/re.rdoc).
Simplifyingregexes
Strategy:namethem,thencombinethem.
f l o a t=/ [ \ d ] + \ . [ \ d ] + / c o m p l e x=/ [ + ] # { f l o a t } \ . # { f l o a t } /
en.wikibooks.org/wiki/Ruby_Programming/Print_version 121/126
10/24/13
Helperwebsites
"rubular":http://rubular.comletsyoutestyourregexpsonline
AlternativeRegularExpressionLibraries
Someotherwrappersexist: PCRE(http://github.com/rdp/pcre)BoostRegex(http://github.com/michaeledgar/rubyboostregex)
RubyVM
RubyVMis(asnoted)veryVMdependent.Currentlyitisdefinedonlyfor1.9.xMRI.
RubyVM::InstructionSequence.disassemble
Availableon1.9only,thisisbasicallyawrapperforyarv.
> >c l a s sA ;d e fg o ;e n d ;e n d > >b=A . n e w . m e t h o d ( : g o ) = ># > >p r i n tR u b y V M : : I n s t r u c t i o n S e q u e n c e . d i s a s s e m b l eb = =d i s a s m := = = = = = = = = = = = = = = = = = = = = = = 0 0 0 0t r a c e8(1 ) 0 0 0 2p u t n i l 0 0 0 3t r a c e1 6(1 ) 0 0 0 5l e a v e
IbelievethosetracemethodsrepresentcallstoanyKernel#set_trace_func(ortheCsiblingtothatrubymethod). Alsonotethatwith1.9.2youcanpassinaproc.
String
StringClass
Methods:
crypt(salt ).Returnsanencodedstringusingcrypt(3). salt isastringwithminimallength2.If salt startswith"$1$",MD5encryptionisused,basedonupto eightcharactersfollowing"$1$".Otherwise,DESisused,basedonthefirsttwocharactersof salt .
Struct
en.wikibooks.org/wiki/Ruby_Programming/Print_version 122/126
10/24/13
Struct
Pleaseseetherdoc(http://rubydoc.org/core/classes/Struct.html)forStruct.Addanyfurtherexamples/tutorialshere.
StructStruct::Tms
RubyProgramming/Reference/Objects/Struct/Struct::Tms
Symbol
Symbols ARubysymbolistheinternalrepresentationofaname.Youconstructthesymbolforanamebyprecedingthenamewithacolon.Aparticularnamewill alwaysgeneratethesamesymbol,regardlessofhowthatnameisusedwithintheprogram.
: O b j e c t : m y V a r i a b l e
Otherlanguagescallthisprocess``interning, andcallsymbols``atoms.
Time
c l a s sT u e s d a y s a t t r _ a c c e s s o r: t i m e ,: p l a c e d e fi n i t i a l i z e ( t i m e ,p l a c e ) @ t i m e=t i m e @ p l a c e=p l a c e e n d e n d f e b 1 2=T u e s d a y s . n e w ( " 8 : 0 0 " ," R i c eU . " )
10/24/13
c a s et i m e . c l a s s . t o _ s w h e n" A r r a y " @ t i m e=T i m e . g m (* t i m e) w h e n" T i m e " @ t i m e=t i m e e l s e t h r o w" i n v a l i dt i m et y p e " e n d e n d a t t r _ a c c e s s o r: t i m e ,: p l a c e e n d # #E v e n ta t5 : 0 0 P M2 2 2 0 0 9 C S T f u n S t a r t=E v e n t . n e w (" e v a n h o d g s o nd a y " ,[ 0 , 0 , 1 7 , 2 , 2 , 2 0 0 9 , 2 , n i l , f a l s e , " C S T " ]) # #E v e n tn o w ,( s e et i m e = T i m e . n e w-t h ed e f a u l ti nc o n s t r u c t o r ) r i g h t N o w=E v e n t . n e w (" N O W ! ") ; # #Y o uc a nc o m p a i r eE v e n t # t i m et oa n yT i m eo b j e c t ! ! i fT i m e . n e w>f u n S t a r t . t i m e p u t s" W e ' r et h e r e " e l s e p u t s" N o ty e t " e n d # #B e c a u s et h ec o n s t r u c t o rt a k e st w of o r m so ft i m e ,y o uc a nd o # #E v e n t . n e w (" R i g h tn o w " ,T i m e . g m ( s t u f fh e r e ))
Thread Thread
TheThreadclassinRubyisawrapper/helperformanipulatingthreads(startingthem,checkingforstatus,storingthreadlocalvariables). Here(http://rubylearning.com/satishtalim/ruby_threads.html)isagoodtutorial. NotethatwithMRI1.8,Rubyused"greenthreads"(pseudothreadsreallysinglethreaded).With1.9,MRIuses"nativethreadswithaglobalinterpeterlock" so"typicallysinglethreaded".Jrubyusestrueconcurrentthreads.IronRubyusestrueconcurrentthreads.RubiniushasthreadingcurrentlylikeMRI1.9.See here(http://www.igvita.com/2008/11/13/concurrencyisamythinruby/)foragoodbackground. Because1.8usesgreenthreadsthismeansthat,forwindows,any"C"call(likegets,puts,etc.)willblockallotherthreadsuntilitreturns.Theschedulercan onlyswitchfromthreadtothreadwhenitisrunningrubycode.However,youcanrunsubprocessesinathreadanditwillwork,andyoucanrunselectandit willstillbeabletoswitchamongthreads.ForLinuxthismeansthatyoucanselecton$stdinandthusnotblockforinput.Forwindows,though,you'rereally stuck.Anykeyboardinputwillblockallotherthreads.With1.9thisisn'tasmuchofaproblembecauseoftheuseofnativethreads(thethreaddoingtheIO callreleasesitsholdontheGILuntiltheIOcallreturns).YoucanuseJruby[1]foranonblocking1.8. With1.9youcanget"around"theglobalthreadlockbywrappingaCcallinrb_thread_blocking_region(thiswillbasicallyallowthatthreadto"gooffanddoits en.wikibooks.org/wiki/Ruby_Programming/Print_version 124/126
10/24/13
Threadlocalvariables
Ifyouwanttostartathreadwithaspecificparameterthatisuniquetothatthread,youcoulduseThread.current
T h r e a d . n e w{ p u t sT h r e a d . c u r r e n t#u n i q u e ! }
Oryoucanstartitwithaparameter,like
t h=T h r e a d . n e w ( 3 3 ){ | p a r a m e t e r | t h r e a d _ u n i q u e _ p a r a m e t e r=p a r a m e t e r }
Thisavoidsconcurrencyissueswhenstartingthreads,forexample
#B R O K E N f o rxi n[ 1 , 2 , 3 ]d o T h r e a d . n e w{ p u t sx#p r o b a b l ya l w a y so u t p u t s3b e c a u s ex ' sv a l u ec h a n g e sd u et ot h eo u t s i d es c o p e } e n d
Joiningonmultiplethreads
Forthisone,usetheThreadsWaitclass(http://rubydoc.org/core/classes/ThreadsWait.html).
r e q u i r e' t h w a i t ' T h r e a d s W a i t . j o i n _ a l l ( t h 1 ,t h 2 ,t h 3 )d o| t h _ t h a t _ j u s t _ e x i t e d |#c o u l da l s oc a l li tl i k ej o i n _ a l l ( [ t h 1 ,t h 2 ,. . . ] ) p u t s' t h r e a dj u s te x i t e d ' ,t h _ t h a t _ j u s t _ e x i t e d e n d #a tt h i sp o i n tt h e yw i l la l lb ed o n e
ControllingConcurrency
en.wikibooks.org/wiki/Ruby_Programming/Print_version 125/126
10/24/13
SeetheMutexclassforhowtocontrolinteractionbetweenthreads.
TrueClass
TheonlyinstanceofTrueClassistrue. Methods:
t r u e&o t h e r-L o g i c a lA N D ,w i t h o u ts h o r tc i r c u i tb e h a v i o r t r u e|o t h e r-L o g i c a lO R ,w i t h o u ts h o r tc i r c u i tb e h a v i o r t r u e^o t h e r-L o g i c a le x c l u s i v eO r( X O R )
Retrievedfrom"http://en.wikibooks.org/w/index.php?title=Ruby_Programming/Print_version&oldid=2451853"
Thispagewaslastmodifiedon1December2012,at20:33. TextisavailableundertheCreativeCommonsAttribution/ShareAlikeLicenseadditionaltermsmayapply.Byusingthissite,youagreetotheTermsof UseandPrivacyPolicy.
en.wikibooks.org/wiki/Ruby_Programming/Print_version
126/126