Professional Documents
Culture Documents
RubyTutorialwithCodeSamples
RubyfortheAttentionDeficitDisorderProgrammerlet'sstartlearning
Rubyfast!
"Javaisapairofscissors,Rubyisachainsaw."
1.InstallRuby
ForwindowsyoucandownloadRubyfrom
http://rubyforge.org/frs/?group_id=167forLinuxtry
http://www.rpmfind.net.
2.Ourfirstprogram
Enterthefollowingintothefile,"test.rb".
AttheC:promptenter,
:>.
Thisproduces:
Howdy!
OK,daylight'sburning,let'smoveon.
3.OutputinRuby
"puts"writestothescreenwithacarriagereturnattheend.
"print"doesthesamethingwithoutthecarriagereturn.
"printf"formatsvariableslikeinCandJava5.
(
%.
Thisproduces:
putsworks
withlinebreaks.
http://www.fincher.org/tips/Languages/Ruby/ printworkswithnolinebreaks.
1/31
12/14/2015
RubyTutorialwithCodeSamples
printworkswithnolinebreaks.
printfformatsnumberslike3.14,andstringslike
me.
4.ReadingfromtheConsole
Use"gets"
$name=.
+$name
5.Functions
A.OurfirstRubyfunction
'def'startsthedefinitionofamethod,and'end'endsitno
cutelittlecurlybraces.
def()
#insidedoublequotes,#{}willevaluatethevariable
end
()#traditionalparens
ThisProduces:
howdynana
B.Parenthesesareoptional
def()
#insidedoublequotes,#{}willevaluatethevariable
end
#look,ma,noparentheses
ThisProduces:
howdyvisitor
Thesameistrueofmethodswithoutarguments
.()=>
.=>
C.Howtoreturnvaluesfromafunction
Wecanusethefaithful'return'
http://www.fincher.org/tips/Languages/Ruby/
2/31
12/14/2015
RubyTutorialwithCodeSamples
def(,)
=*
return
end
(2,3)=>6
Oddlyenoughyoucanleaveoutthe"return"statement,and
Rubywillhelpfullyreturnthelastexpression:
def(,)
=*
end
(2,3)
orevensimpler,leaveout"product"andrubyreturnsthe
contentsofthelastexpression:
def(,)
*
end
(3,3)=>9
D.Optionalargumentvalues
Rubyletsyouassignvaluestoargumentswhichmay,ormay
notbesuppliedasshownbelow:
def(=1,=2,=+)
end
=>1,2,3
5=>5,2,7
4,6=>4,6,10
3,4,6=>3,4,6
E.Extraarguments
Extraargumentsaregatheredintothelastvariableif
precededwitha"*".("each"isaniteratorthatloopsoverits
members).
def(=1,=2,*)
.{||}#Wewilllearnabout"each"verysoon.Ipromise
end
3,6,9,12,15,18
Thisproduces:
3,6
9,12,15,18,
http://www.fincher.org/tips/Languages/Ruby/
3/31
12/14/2015
RubyTutorialwithCodeSamples
F.Multiplereturnvalues
def
=30000#somefancydbcallsgohere
=30
return,
end
,=
Produces:
=30000,=30
6.OpenClasses
Youcanaddmethodstoexistinglibraryclasses.Forexample,in
C#2.0,Microsoftaddedtheveryhelpfulstringfunction,
IsNullOrEmpty()whichreplacestheunwieldlyconstruct:
if(mystring!=null&&mystring!="")
InRubyyoudon'thavetowaitforthemavensinRedmondtodecide
youneedanewstringfunction,youcanaddityourself.
class
defNullOrEmpty?
(self==nil||self==)
end
end
.NullOrEmpty?
.NullOrEmpty?
Isthiswaycool?Yes.Isthisverydangerous?Yes.Remember,
Rubyisachainsaw.
7.Variablenaming
Ok,let'sslowdownandlearnsomebasicsaboutvariablenames
A.Globalvariablesstartwith'$'
B.Classvariablesstartwith'@@'
C.Instancevariablesstartwith'@'
D.Localvariables,methodnames,andmethodparametersstart
withalowercaseletter
E.Classnames,modulenamesandconstantsstartwithan
uppercaseletter
F.Variablesnamesarecomposedofletters,numbersand
underscores
G.Methodnamesmayendwith"?","!",or"=".Methodsending
witha"?"implyabooleanoperation(eg,"instance_of?").
Methodsendingwith"!"implysomethingdangerous,like
stringsbeingmodifiedinplace(eg,"upcase!")
8.InterestingtidbitsaboutRuby,
http://www.fincher.org/tips/Languages/Ruby/
4/31
12/14/2015
RubyTutorialwithCodeSamples
A.'#'isthelinecommentcharacter,allcharactersafterthisare
ignored.Confusingly'#'canappearwithinquoteswitha
differentmeaning.
B.Nosemicolonsareneededtoendlines,butmaybeusedto
separatestatementsonthesameline
C.Abackslash(\)attheendofalineisusedforcontinuation
D.Indentingisnotsignificant,unlikepython
E.Typesofvariablesdonotneedtobedeclared
F.Linesbetween=beginand=endareignored
G.Linesfollowing"__END__"onitsownlinewithnowhite
space,areignored
H.Atinydemonstrationofthese:
#sampleprogramshowingspecialcharacterslikecomments
#I'macommentline
=1#noticenosemicolonandnotypedeclaration
=2=3#noticetwostatementsononeline
=
=begin
I'mignored.
SoamI.
=end
1
2
3
4
9.VariableTypes
InRuby,variablesdon'thaveaspecifictypeassociatedwiththem.
Allvariablesareobjects,soweonlyplaywithpointerstothose
objects,andthosepointersaretypeagnostic.
=
=1.23
11.Quotes
LikeinPerl,singlequotesanddoublequoteshavedifferent
meanings.
Doublequotesmeans"pleaseinterpretspecialcharactersinthis
string".Thingslikebackslashn('\n')areconvertedtotheirtypical
values.The#{name}constructisconvertedtoitsvalue.
Withsinglequotes,nospecialcharactersareinterpreted.
Examples:
http://www.fincher.org/tips/Languages/Ruby/
5/31
12/14/2015
RubyTutorialwithCodeSamples
=
=>
=>(return)
=>\#{name}(nosubstitutionsaremadesinceusingsingl
Thebracesareoptionalforglobalandinstancevariables
$myname=
=>
12.Objects
AgreatthingaboutRubyisthatnumbersandstringsarereal
objects.
1.5.()=>
Thisletsusdosomecoolthings.Insteadof
if(>7&&
Wecanwrite
if.between?(7,12)do...
13.BigNumbers
Rubyautomaticallyincreasestheprecisionofvariables
forin1..1000
end
Produces:
2**1=2
2**2=4
2**3=8
2**4=16
2**5=32
2**6=64
2**7=128
2**8=256
2**9=512
2**10=1024
...
2**1000=107150860718626732094842504906000181056140481170553360744375
35984577574698574803934567774824230985421074605062371141877954182153046
37205668069376
http://www.fincher.org/tips/Languages/Ruby/
6/31
12/14/2015
RubyTutorialwithCodeSamples
Rubywillincreasetheprecisionofthenumber,ordecreaseitas
needed:
=1000000
+.class.=>1000000
=*
+.class.=>1000000000000
=/1000000
+.class.=>1000000
14.ParallelAssignment
Youcanswapthevaluesinvariableswithouttheuseofatemp
variable.Rememberyourfirstprogrammingclass:Swapthevaluesin
"i"and"j"?Youhadtousea"t"variabletostoreoneofthevalues
first.NotneededinRuby.
=0
=1
,=,
Produces:
=0,=1
=1,=0
15.Collections
A.Arrays
a.Anarrayofknownobjectscanbecreatedbyenclosingthem
insquarebrackets.
=[1,2.0,]
[2]=>
Rubyarrays,likeallrightthinkingcollections,arezero
based.
b.
Youcanusenegativeindexestostartfromtheendofthe
array
=[1,2.0,,]
[1]=>
Using"1"issomuchmoreconcisethan
"nums[nums.length()1]".
c.Youcanevenusethehandy"first"and"last"methods.
http://www.fincher.org/tips/Languages/Ruby/
7/31
12/14/2015
RubyTutorialwithCodeSamples
[1,2,3].=>3
[1,2,3].=>1
d.length
Togetthecount,orsize,ofanarray,usethe"length"
method.
=[,,]#makeastringarray
.=>3
e.%wshortcut
Sincemanyarraysarecomposedofsinglewordsandall
thosecommasandquotemarksaretroublesome,Ruby
providesahandyshortcut,%w:
=%{}#makeastringarray
f.inspect
Tolookatcontentsofanobjectusethe"inspect"method.
Evenmoreconvenientistouse"p"asashorthandfor"puts
obj.inspect"
=[1,2,5,7,11]
.
Produces:
1
2
5
7
11
[1,2,5,7,11]
[1,2,5,7,11]
g.Arrayscanactlikequeuesandsets
#&istheintersectionoperator
[1,2,3]&[3,4,5]#prints3
#+istheadditionoperator
[1,2,3]+[3,4,5]#prints1,2,3,3,4,5
#removesitemsfromthefirstarraythatappearinthesecond
[1,2,3][3,4,5]#prints1,2
#popreturnsthelastelementandremovesitfromthearray
=[,,,,,]
+.#pop=f
http://www.fincher.org/tips/Languages/Ruby/
8/31
12/14/2015
RubyTutorialwithCodeSamples
.#["a","b","c","d","e"]
#pushappendselementstotheendofanarray
=[,,]
.(,,)
.#["a","b","c","x","y","z"]
#shiftreturnsthefirstelementandremovesitfromthearray
=[,,,,,]
+.#shift=a
.#["b","c","d","e","f"]
#unshiftappendselementstothebeginningofanarray
=[,,]
.(,,)
.#["x","y","z","a","b","c"]
B.Hashes
Thistypeofcollectionisalsocalledadictionaryoran
associativearray.
a.Simplehashofcarsandtheirmakers
={
=>,
=>,
=>
}
[]=>
b.Youcancreateahashandfillitdynamically
={}#createanewdictionary
[]=#associatethekey'H'tothevalue'Hydrogen'
[]=
[]=
[]#prints"Hydrogen"
.#prints3
.#prints["Lithium","Helium","Hydrogen"]
.#prints["Li","He","H"]
#prints{"Li"=>"Lithium","He"=>"Helium","H"=>"Hydrogen
c.Hash[]
YoucanalsocreateHasheswithsquarebracketsby
prefixingwith"Hash":
=[,,,,
.
Produces:
{=>,=>,=>
http://www.fincher.org/tips/Languages/Ruby/
9/31
12/14/2015
RubyTutorialwithCodeSamples
d.each
The"each"methodisawonderfulwaytoiterateoverthe
keys
=[,,,,
.{|,|
Produces:
e.select
The"select"methodpopulatesanewarraywith
memberswhichmeetacriteria
=[,10.9,,7.5,,6.0,,6.5
.
=.{|,|>7.0
.#prints[["larry",7.5],["bob",10.9]]
C.Ranges
Rangesarecomposedofexpr..exprorexpr...expr.Twodots
includesthelastelement,threedotsexcludesit.
(..).{||}
Produces:
(1...3).{||}
Producesonlytwonumberssince"..."doesnotincludethe
lastelement.:
1
2
http://www.fincher.org/tips/Languages/Ruby/
10/31
12/14/2015
RubyTutorialwithCodeSamples
16.ControlStatements
A.ifInan"if"statementanythingbutthetwospecialvalues,
"false"and"nil"areconsideredtrue.Evenzeroistrueforall
youC/C++programmers.
=30000.00
if
=0.02
elsif
=0.28
else
=0.5
end
B.case
=10
=case
when0..5
when6..8
when9..12
else
end
C.for
forin1..4
end
Therangescanofcoursehavevariables
=6
forin1..
end
D.exit
=.()
if.
2
end
.
http://www.fincher.org/tips/Languages/Ruby/
11/31
12/14/2015
RubyTutorialwithCodeSamples
E.loop
iteratesovercodeuntila"break"oreternityends
=0
loopdo
breakif>5
+=1
end
17.Statementmodifiers
Thesearejustsyntaticsugar.
A.if
The"if"clausemaybeplacedattheendofastatement
=10.0
if
B.unless
"unless"isplacedattheendofastatement
=10.0
unless>0.0
C.while
"while"maybeafteritsblock
=2
=+2while
=>4
=>6
=>8
=>10
18.Iterators
A.while
=0
while
=+1
end
B."times"
=10
.{||}
http://www.fincher.org/tips/Languages/Ruby/
12/31
12/14/2015
RubyTutorialwithCodeSamples
Produces:
0123456789
C."each"
=%()
.{||}
lionstigersbears
D."each"withranges
(..).{||}
mnopqrstuvwxyz
E."upto"
=0=7
.(){||}
01234567
19.Yougottahaveclass.
A.Classes
Classdefinitionsstartwith"class"andendwith"end".
Rememberthatclassnamesstartwithacapitalletter.Noticethe
syntaxis"object.new"forcreatinganobjectandthatthe
"initialize"methodcontainscodenormallyfoundinthe
constructor.Here'sasmallexample:
class
def(,)
@fname=
@lname=
end
end
=.(,)
Produces:
#<Person:0x257c020>
http://www.fincher.org/tips/Languages/Ruby/
13/31
12/14/2015
RubyTutorialwithCodeSamples
whichistrue,butnothelpful.
B.The"ToString"method,to_s
class
def(,)
@fname=
@lname=
end
def
end
end
=.(,)
Produces:
Person:AugustusBondi
C.Subclassing
InRubysubclassingisdonewiththe"<"character
class
def(,,)
super(,)
@position=
end
def
super+
end
end
=.(,, )
Produces:
Person:AugustusBondi,CFO
ifwetrytoprintthefirstnamedirectlylike
.
wegettheerrormessage,
.:21:
Butwhyisthat?We'veprintedvariablesazilliontimesuptil
nowandit'salwaysworked.Whatchanged?Upuntilnowwe've
createdvariablesinaprogramwithoutclasses(actuallyallare
variablesweremembersofadefaultobjectthatwereaccessable
http://www.fincher.org/tips/Languages/Ruby/
14/31
12/14/2015
RubyTutorialwithCodeSamples
insideitself).Nowweareusingrealclassesandthatbringsup
thepointofvisibilityofmembersoutsidetheclass.Wenowhave
tospecifyifavariableisopentotheoutside,like"public",
"private","protected","internal"inotherlanguages.
Tograntaccesstoreadavariablewedeclareitafter
"attr_reader".attributewiththefollowing:
:,:
then
.=>
Toallowwritingtoavariableuse"attr_writer",
class
def(,,)
super(,)
@position=
end
def
super+
end
:
end
=.(,, )
.
.=
D.VirtualAttributes
class
def(,,)
super(,)
@position=
end
def
super+
end
:
def
if@position==||@position==
else
end
end
end
=.(,, )
.=
.=>
.=
http://www.fincher.org/tips/Languages/Ruby/
15/31
12/14/2015
RubyTutorialwithCodeSamples
.=>
20.RegularExpressions
Stringscanbecomparedtoaregularexpressionwith"=~".
Regularexpressionsaresurroundedby"//"or"%r{}".Anythingbutthe
twospecialvalues,"false"and"nil"areconsideredtrue.
Expression
Result Description
/a/=~"AllGaulisdivided
intothreeparts"
findsthefirst"a"atposition
5
%r{a}=~"AllGaulisdivided
intothreeparts"
samethingwithalternate
syntax
/ree/=~"AllGaulisdivided
intothreeparts"
27
finds"ree"atposition27
/^a/=~"AllGaulisdivided
intothreeparts"
nil
"^"impliesatthebeginning
ofaline.nilisfalse.
/^A/=~"AllGaulisdivided
intothreeparts"
casesensitive,remember
that"0"istrue
/s$/=~"AllGaulisdivided
intothreeparts"
35
"$"impliesattheendofa
line
/p.r/=~"AllGaulisdivided
intothreeparts"
31
"."matchesanycharacter
21.Blocks
AndnowtooneofthecoolestthingsaboutRubyblocks.Blocks
arenamelesschunksofcodethatmaybepassedasanargumentto
afunction.
A.SimpleExample
def
yield
yield
yield
end
{}
Produces:
money?
money?
money?
Intheaboveexample'{puts"whereisthemoney?"}'iscalled
ablock.Thatchunkofcodeispassedtothemethod"whereisit"
andexecutedeachtimethe"yield"statementisexecuted.You
canthinkofthe"yield"beingreplacedbytheblockofcode.
B.Blockscantakearguments
Herethemethod"cubes"takesthemaxvalue.
http://www.fincher.org/tips/Languages/Ruby/
16/31
12/14/2015
RubyTutorialwithCodeSamples
def()
=1
while
yield**3
+=1
end
end
(8){||,}=>1,8,27,64,125,216,343,
=0
(8){||+=}
,=>=784
=1
(8){||*=}
,=>=128024064000
Thinkofthe"yieldi**3"inthefunctioncubesasbeing
replacedwiththeblock,'|x|printx,","'.Thevaluefollowingthe
"yield"ispassedasthevalue"x"totheblock.
C.Multipleargumentsmaybepassedtoblocks.
def()
#next2linessimulatedfromcallingadatabaseontheempId
=
=
yield,#multipleargumentssenttoblock
end
(4){|,|,,,,
Produces:
:
D.Localvariablescanbesharedwithablock
Eventhoughrateisalocalvariable,itisusedinsidethe
block.
def()
yield
end
=0.15
=(10.0){||*}
,
Produces:
:1.5
E.Blocksarebuiltintomanyobjectsinruby
a.each
http://www.fincher.org/tips/Languages/Ruby/
17/31
12/14/2015
RubyTutorialwithCodeSamples
iteratesthrougheachitemofacollection
[1,2,3,4].{||**2,}
Produces:
14916
b.detect
returnsthefirstitemmatchingalogicalexpression
=[1,3,5,8,10,14]
=.{||>9}
=>10
c.select
returnsallitemsmatchingalogicalexpression
=[1,2,3,4,5,6,7]
=.{||%2==0}
=>[2,4,6]
d.collect
returnsanarraycreatedbydoingtheoperationoneach
element.
[1,2,3,4].{||**3}=>[1,8,27,64]
[,,,].{||.}=>[
e.inject
"inject"isthe"fold"or"reducer"functioninRuby."inject"
loopsoveranenumerableandperformsanoperationon
eachobjectandreturnsasinglevalue.
=[1,3,5,7,11,13]
#using"inject"tosum.Wepassin"0"astheinitialvalue
=.(0){|,|+
=>40
#wepassinnoinitialvalue,soinjectusesthefirstelement
=.{|,|*
=>15015
#justforfunlet'ssumallthenumbersfrom1to,oh,sayamillion
=(1..1000000).(0){|,|+}
=>500000500000
#youcandointerestingthingslikebuildhashes
=.({}){|,|.({.=>})}
#=>{"11"=>11,"7"=>7,"13"=>13,"1"=>1,"3"=>3,"5"=>5}
http://www.fincher.org/tips/Languages/Ruby/
18/31
12/14/2015
RubyTutorialwithCodeSamples
22.FileI/O
A.Readanentirefileintoastring
= .()
=.
B.Readanentirefileintoanarrayoflines
=.()
[0]#printsthefirstline
C.Readafilelinebyline
= .()
while=.
end
OryoucanusetheIOclass
.(){||}
D.Readafilelinebyline
Youshouldensurethefileisclosedaswell.
begin
= .()
while=.
end
ensure
.
end
E.Readonlyafewbytesatatime
Thefollowingsnippetofcodereadsafilewhichmayhaveno
linebreaksandchopsitinto80characterlines
require
= .()
while=.(80)
+
end
.
F.ReadsalargeXMLfileandinsertslinebreaks
UsesTruncatedDataErrortograbthelastfewslackerbytes
fromtheend.
http://www.fincher.org/tips/Languages/Ruby/
19/31
12/14/2015
RubyTutorialwithCodeSamples
#readsanxmlfilewithoutlinebreaksandputsalinebreakbeforeeach'<'
require
= .()
begin
while=.(80)
.(,)
end
rescue#thelastreadhadlesscharsthanspecified
#printtherestofthedata.$!istheexception.
#".data"hastheextrabytes
!..(,)
ensure
.unless.nil?
end
23.method_missingawonderfulidea
Inmostlanguageswhenamethodcannotbefoundanderroris
thrownandyourprogramstops.Inrubyyoucanactuallycatchthose
errorsandperhapsdosomethingintelligentwiththesituation.Atrivial
example:
class
def(,)
return+
end
def(,*)
end
end
=.
.(1,4)
.(4,2)
Produces:
5
nil
24.
Whiletherubyprogramisloading,youcanexecutecodeinsidea
specialblocklabeled"BEGIN"prettynifty.Aftertheinterpretorhas
loadedthecode,butbeforeexecution,youcanexecutecodeinthe
"END"block.
END{
}
BEGIN{
}
http://www.fincher.org/tips/Languages/Ruby/
20/31
12/14/2015
RubyTutorialwithCodeSamples
Produces:
25.convertingbetweenstringsandints
Usetheto_iandto_smethods
.#returnaninteger
3.#returnsastring
26.UsingXMLDomParser
REXMLgoesstandardwithRuby1.8.Sampletoprintall"div"
elementswhose"class"attributeissetto"entry".
require
= .()
=::.
..(){||
27.Runafewlinesdirectlyfromthecommandlinewiththe"e"
option
:\\>
:\\>
12
:\\>
12
16
28.Editingfilesinplace
Rubyoffersasimplewaytomakeastringsubstitutioninmany
filesallatoncewithasinglelineofcode.The"p"optionloopsover
thefiles,the"i"isthebackupextension.Withthiscommandweare
changingallthedocumentationfromversion1.5to1.6,butthe
originalfilesarerenamedto".bak".
:\\\>.
1.5...
....
1.5
:\\\>.*.
:\\\>.
1.6...
....
1.6
http://www.fincher.org/tips/Languages/Ruby/
21/31
12/14/2015
RubyTutorialwithCodeSamples
:\\\>..
1.5...
....
1.5
29.Exampleofprintingduplicatelinesinsortedfile.
#printsduplicatelinesinsortedfilesinthefilepassedinasfirstarg
= .(
[0])
=
=0
while=.
+=1
if==
end
=
end
30.Rubyhasitsowninterpretedshell,irb.
:\\>
():001:0>
=>nil
():002:0>=1
=>1
():003:0>*2
=>2
():004:0>
31.rubycantakeinputfromstdin
|
32.topassastringontheurlitneedstobe"escape"'dfirst.
require
...
.()
33.Exampletoremove"funny"charactersfromafilename
Exampleofiteratingoverthefilenamesinadirectory,using
regularexpressionsubstitutioninstrings,andrenamingfiles.
#replacesany"funny"charactersinafilenameinthecurrentdirectorywithanunderscore
#ifthenewfilenamealreadyexists,thisskipsit.
http://www.fincher.org/tips/Languages/Ruby/
22/31
12/14/2015
RubyTutorialwithCodeSamples
.(){||
if=~#filenamecontainssomethingotherthanletters,numbers,_,
=.(,)#\wisanywordcharacter,letter,numor
if .exist?()
else
.(,)
end
else
end
}
34.Loopingoverlistofarguments
.{||
=0
= .(,)
=+
= .(,)
while=.
if=~
+=1
=.(,)
end
.
end
.
.
.(,)
}
35.MiscellanousCommands
command
description
example result
global_variables returnsallglobalvariables
local_variables
returnsalllocalvariables
sleepseconds
sleepsspecifiedseconds
rand
returnsarandomnumber
between0and1
rand(max)
returnsintbetween0andmax
warn
likeprint,butwritestoSTDERR
Interestingstringfunctions
command description
http://www.fincher.org/tips/Languages/Ruby/
example
result
23/31
12/14/2015
RubyTutorialwithCodeSamples
center
centersstring
"City".center(20)
"________City________"
ljust
leftjustifies
"State".ljust(30)
"State_________________________"
rjust
rightjustifies
"State".rjust(30)
"_________________________State"
include?
doesthestring
"thisisatest".include?
includethis
('is')
substring
gsub
globalregex
"thisisa
th_s_s_t_st
replacesments test".gsub(/[aeiou]/,'_\1')
tr
translates
each
splitsand
iterates
"Thegreatestofthese
is".tr('aeiou','*')
true
Th*gr**t*st*fth*s**s
"one:two:three".each(':') one:
{|x|putsx}
two:
three
36.DateTime
.#prints20061125T14:26:150600
.#prints20061125
.#printsSatNov2514:29:57CentralStandardTime2006
37.Using'require'
requirewillletyouraccesscodefromotherfiles.'require'looksin
directoriesspecifiedin$LOAD_PATHtofindthefiles.The
environmentalvariableRUBYLIBcanbeusedtoloadpathsinto
$LOAD_PATH.
:\\\>
():001:0>$LOAD_PATH
[,
,]
=>nil
Youcanputalibrarylike'startClicker.rb'inanyofthosedirectories
andrubywillfindit.
require
38.BuiltInCommandInterpreter
Withthe"eval"methodyoucancreateyourowninterpreter
languageandrunitduringexecution.
():007:0>=6
=>6
():008:0>=7
=>7
():009:0>
http://www.fincher.org/tips/Languages/Ruby/
24/31
12/14/2015
RubyTutorialwithCodeSamples
=>13
():010:0>
13
39.IntrospectionwithObjectSpace
Youcanfindalltheobjectsinyourprogramofaparticulartype
usingObjectSpace.each_object.
class
def(,)
@name=
@age=
end
:
end
=.(,34)
=.(
,31)
.(){||
.
}
Produces:
40.Testing
Rubycomesrightoutoftheboxwithatestingframework.Here'sa
quickexample:
require
class
def
=1+1
(2,)
end
end
41.ReadaURLandprintthewebpagetothescreen.
Thiswillgetaparticularpageandprinttothescreen:
require
(){||.}
Thiswillreadafileofurlsandprintalltothescreen:
#Readsfirstargumentasfilecontainingurlsandprintsthem
http://www.fincher.org/tips/Languages/Ruby/
25/31
12/14/2015
RubyTutorialwithCodeSamples
#usage:rubywget.rbwget.txt
require
.(
[0]){||(){||.}}
42.ExampleofdrawingalineonacanvasinTk
TkisagraphicalsubsystemusedinlanguageslikePerlandTcl.
#drawsasinglelineonabigcanvas
require
include
.do||
=.()do||
600
600
(=>,=>,=>)
=[]
end
.(,0,0,100,100)
end
.
43.irbinteractiveruby
RubycomeswithanREPL(ReadEvalPrintLoop)utilitytoletyou
tryrubyinteractively.("infruby.el"providesaninternalshellinemacs
forirb).
:>
():001:0>
nil
():002:0>.
.
[,,,,,
():003:0>
44.RubyGemsarubypackageinstaller
YoucandownloadRubyGemsfromhttp://rubyforge.org.Unzipthe
files(eg,C:\opt\ruby)theninstallbyentering:
:>:\\\0.9.0
:\\\0.9.0>.
45.RubyonRails
A.Howtowritealogmessage
Youcanuselogger'smethods"warn","info","error",and
"fatal".
http://www.fincher.org/tips/Languages/Ruby/
26/31
12/14/2015
RubyTutorialwithCodeSamples
.(+.)
B.Fieldnamesendingwith"_at"areassumedtobedatetime
fieldsandarefilledinautomagicallybyrailsforActiveRecord
objects.Thesuffix"_on"areassumedtobedates.
C.Console
todubugapplicationsit'sconvenienttousetheconsolescript
>/
D.debugmethod
Youcanusethedebug()methodinsidewebpagestodump
infoaboutanobject.
for
E.HowtoFreezeaversion
Sinceyourhostingcompanymayupgradetherailsversion
youneedto"freeze"thecurrentversion.Thefollowingcopiesall
the1.2.6librariesfromtheshareddirectorytoyourownprivate
one.
::
=26
F.Activerecordnotes
a.
Findallrecordsmeetingacriteria
defself.()
if==
(:,
:=>,
:=>
)
elsif==
(:,
:=>,
:=>
)
else
(:,
:=>,
:=>
)
end
end
Thefirstargumenttofindcanalsobe":first"or":last".
b.Findthecountofrecordsmeetingacriteria
http://www.fincher.org/tips/Languages/Ruby/
27/31
12/14/2015
RubyTutorialwithCodeSamples
defself.()
()
end
defself.()
()
end
Findthetotalnumberofitems
=
.
Findthetotalnumberofitemsmeetingacriteria
=
.([])
c.Pagination
The":limit"and":offset"optionsalloweasypagination.
Toreturnthefifthpageofitemsusethefollowing:
(:,
:=>,
:=>,
:=>10,
:=>40
)
d.UserawSQLandreturntwovalues
def
=.([
return[0]..,[0]..
end
e.The"create"methodinActiveRecordwilldo"new"and
"save"operationssimultanously.
=.(
:=>
:=>
)
G.Watir
WatirisaGUItestingtoolwritteninRuby.Hereisascriptto
openGoogleandsearchforpicturesofkittens.
require
=::.#createanobjecttodrivethebrowser
.
.==
http://www.fincher.org/tips/Languages/Ruby/
28/31
12/14/2015
RubyTutorialwithCodeSamples
.(:,).#flashtheitemtext"Images"
.(:,).#clickonthelinktotheimagessearchpage
..include?
=#setavariabletoholdoursearchterm
.(:,).()#qisthenameofthesearchfield
.(:,
).#"btnG"isthenameofthegooglebutton
if.()
else
end
H.SelectingaJavaScriptpopupbox
stolenfromhttp://wiki.openqa.org/display/WTR/FAQ
#WatirscripttoshowclickingaJavaScriptpopupbox
require
require
require
require
require
$ie=::.#createanobjecttodrivethebrowser
$ie.
if$ie.()
$ie.(:,).()
$ie.(:,).()
$ie.(:,).
end
$ie.(:,).
$ie.(:,).
def()
=$ie.(:,)
.()
$ie.(:,).
(,4,)
1
end
()
()
startClicker.rb:
#methodstartClickerfromhttp://wiki.openqa.org/display/WTR/FAQ
def(,=9,=nil)
#getahandleifoneexists
=$ie.()
if()#yesthereisapopup
=.
if()
. (,
end
#Iputthisintoseethetextbeinginputitisnotnecessarytowork
3
http://www.fincher.org/tips/Languages/Ruby/
29/31
12/14/2015
RubyTutorialwithCodeSamples
#"OK"orwhateverthenameonthebuttonis
.(,)
#
#thisisjustcleanup
=nil
end
end
I.HowtouseWatirwithNUnit
HereisanexampleofconnectingittoNUnit.
using
using.
using..
using.
namespace..
{
///<summary>
///from
///withsmallhacksfromLizBuenker
///</summary>
publicclassWatirAssert
{
publicstaticvoidTestPassed(string ,string
{
string=.
using(=newProcess())
{
..=false
..=true
.. =
..= +
..=
.Start()
=..ReadToEnd()
.WaitForExit()
}
.Write()
.Write()
=newRegex(
=.Match()
try
{
int=int.Parse(.
[].)
int=int.Parse(.
[
int=int.Parse(.
[].
int=int.Parse(.
[].
if(>0&&>0)
{
.Fail(.Format(
}
elseif(>0)
{
.Fail(.Format(
}
}
catch()
http://www.fincher.org/tips/Languages/Ruby/
30/31
12/14/2015
RubyTutorialwithCodeSamples
{
.Fail(+.ToString
}
}
}
}
Theabovecodewouldbeusedbysomethinglikethis:
using
using.
namespace..
{
[ ]
publicclassWatirTest
{
privatestaticreadonlystring=.
publicWatirTest(){}
[]
publicvoidSd01Test()
{
.TestPassed(,)
}
[]
publicvoidSd02Test()
{
.TestPassed(,)
}
}
}
46.RubyQuotes:
"Rubyisalanguageforcleverpeople."Matz
"RubyistheperlificationofLisp."Matz
"TypeDeclarationsaretheMaginotlineofprogramming."Mitch
Fincher
http://www.fincher.org/tips/Languages/Ruby/
31/31