You are on page 1of 23

Chntt-6

Ruby
Tntroducdion- ard
a rdl
obect orented LamquagC
Zuby
kuby us a pwe
for procedual , fncttomal
i t is also Suttabh

prorranmming qeneal
high level ,
-

nterprcteo
Rb
,
kiuby us am

puwpost Kamquage
Massumato
Kuby ws developed by yukihero
wm
fea 1995
umato
Kanquage, Mats
nflutmceo b berl
b/
namfor for his
muo

anted to uue a feuoel


Sohemamed Kuby."
Kamquage So
availabla On
frecty
openSouwnce feneralpwpose orteapretd
web and
programmtng
amgua9t
Aamquaqe
hamguage
oriented
preyrammirg
obfcct
-

Trut Scripttng Aamguage


Sever sid
into
nto HTM
tTML
Cam be embeddd

Kub4 harnd
lean Cohich Can be tastly,
to
E aEasy
sy uicky)

Simtlan Spntar to prg n Lang uage (ze

c , perl
Orittorn
Oriten un
Teuby ane
Tuby aie
programmings
>6a
maintained
easily
Useg _Kubr amqu0qe2-
cwcb
Mosttuf sed m buildg /eueloptng
faqes appltcatn tRe (arahyst
T t has othut
Prototimg Proof Comcept

obviou
tmplormuntatton
Ruby
Ruby
Most
base
Rai locb Connecte to D a t a
be casiy
Cam
oracle
59h Pococfu
My ,

Small, elegant
providu

Cod
Iteractive uby
Similae to Unin prograoming
As enpertmentatten
ohi ch
which
Shull for
RI R prwvidu a
vie exprsíon vutt
lne by Lene
immtlta ty
at fow
Lommamd pwmjot am
lrb
Just type
Senion o i l l Stant
ntr atve

Sapatteedh
Saic prgw Coth
th om entenSion.rb

rogam
wser /bn meby -

puts "tlollo
as test, rb
Sav test.rb we
T um the h
uby test.h
Ce--Hello

arquag reperties

hhitespncts Spacea, f tab spacey ant qmerally


iqnootd m nuby, but euept whun Thay ppea

eg atb ntenprttd a att local vartall


a4btnterpated as altb)me thod all)

Program
n endleg Ruby
Somico lon neuwltme Chanatters as ending
Statement
AL pernts Cncounters Suth Cs t y - 8, I - - - . a t

end e a ltnC Th indica-t that Cont'nu Qton


a Statemt

muthod
, Comttaná
Namt
Viablg
Case Sensitive (eg* RAM amlkiporent)

ComtainA alpha Tumerit Choraters 6 t


undursceve
Character

Kuby BEGIN and END Statemnd


Stre BEGINS END

s/nt END S
fease
Exampla
Puts 7matn prg
ENDS
Puts ENDD Íng prq
BEGTN
Puts earrt Py

Start prq
ndedo P
matn fr
Lommen3i
A COmmunt hd%. th lnu or part ef a ne
eY Sevcral lines
at beg noing abin bae
hash #)

New prg
Bey puli php tmgrm

Classe Qmd D6fec


Kuby us poyect obfect ortented prg9wming
tanguag
7h featwm L obfect -tritnted pregrnnmin
lamguage imcludes
ata abstratE(om
nta Encapsulatiom
3 n hvtance
4 polymorphism
An cbject oented prgrmm mwlus clames objenh
hu. prints frem uhich ndividyal
Alan s a
Obj lts u. Crated data mem bers and
a nd
us collection ef
A Class actrstics fenctionality
(o) char
ember function
Sntarc
Clam Customn

uit
las foloud
l a n folloud
Stant-
A clacs in mmby alucnys nmu alusays imrbtal
imittal
tlam. e t l a m
by nami of
Capitals tnd
kiyund Cnt
Teum ivnatting
clam hy t tumttons
mmber f
emom
unl4ons
ber
u
ard ition
hu d a t a memberu
beboun Clam dpo
dyo t'tion
to ortte
haut
Kujuword

Variable in kuby l a
local alabe

Tnstanct ouabas

b ts
Cla wia
4 Global vaiabes

avni labe. AcOSS


acss tte
ocal vaniabl aru
avniable.
vcwmia.blls
Tmstante
o r oect
or olject. e
s
mtsa
tnnne
e
partleulan
Methods Jor any
tor
rom bjeet
ohert to ehece
instarne v a l a bles tloya
vauiabla preredd hy folocoet by
Lstune
Vawúable. mam

Clas uariablts*
clam Vauablu me awailable. atross differerad
oejeed
claK Vauiabd belongs to tt
thu Clas amd ia
A
a charaslerstie a lan
clam Voia,da pYotdrd by @ folloused. by
varlalle nam

Class Custorne
Ca@ e.f.cust - O
dy imétta lize ( td, Tame)
@cust- id- id
Cust. name = nami
cust- addr= add
emd

total_cust C)
def
@0 mo-af-custt = |
Puts Total cutornus ff@no. f_ Cust
end
def display C)
puts customwr id # cust. td
Put Custemu nam. # cust- nam
end
end
Cust 1 Custemur,neuo ( " , ama")
Cust a Castonmn n e w a " , * laKShmi

Cutitotal _ c ustl)j
custa total -custly
eult Total Customn ||
TDtal custom 2

Global Vaniable, :

Global va tabs are begin


oith .
uminittaltred Global variablui
haue tke valut NtL
valut VTL
The Scope o global.
lobal vaúabla entire th program.
Scope Prgram
TD prtnt tt vlabh. valu Lth ln douba

quotes t h vaniabu us p r ecedud


var = ID
$ qlobal -

Class class1
aef prt-global
vasiake vauu is # $qbbal
PLct Global

end
end
class class
d Print qloka!
Puts Global vaiabl tn class a i #
g lobal- var"

end
end
Dbi Class 1 m ew
obl= P i n t . qlobal
Oba= Class a ncw
Oba pmt-global
vartable valus clan1 ia 10
in
Global
valu in clana is l o
Global vasiabll
hstance viab a-

Frstamte variabes beg uwith @


wn inttialtrud Vanlabl hawing hu valut NT
Th Scope tki vasiab L across te
method
TO primt th V a i a b u vau oith im dou ble
uot h variab s precedd by #

eg put"f# vax
Class Cuttomu
dy netiallre [ id, name)
Cust-fd =id
erd Cnd
acut-nami =nann
Pecla
ley display ()
Custom id # custiol;
P u
Puu
end end
turtomv ame, # cust- nmi

Est Customa .n cw1" Rama)


Cust a Custom new (2"" "Lakshmi "
Cust delay)
Cust3 diplay ()
&ult
Curtomed
Cuktomu namt kama
Cuton id a
Cutomn namu Aatshmi

by or fant pperrCast leters


Constam beqin wth wltham
d class Cam be a c e e d
v dpined
7he
cnstant
othorsisc LwC deyined odsid
cwth in lan
from b aated Globa
hOst Can
t t class
tta
not be depineol m methods
Constama may
may
wntialitd cestmt produce am
cro
KeLeremay an
7D print t valu 4
valu a vauiabu wfth in
doub
uotes, thn

eramph Class Sarnpl


Varl= 100
vn2 a00
def Show ()
Pu "valu q var is # vari?

pusvaluu of Vaa is # ? vax a


nd End

ob = Sampe neuw
Db
Show()
elr Valuu D Va1 s

Conditonal Statemenb:
eaecutes th bloch of codl Based en
Cerdition or etprwion
we a
havnq
hatng followimy Cend ttonal Strtemoni

i fi f ele slatemunh
modipier
wnas statemmt
wm leM Modifiev
5 CaAe
elke Slatemint:

f the Condttion i tru otl ezecuta if


block code otlerwise etott erccute ele llock tod

Puts " rate than a"

Pubs x s
ehe
Puk wwe cant qus"
emd
s
ePressions ued to ConoliEfomal execubto
ehe if s Tot ehe
i Moctpier:
T will executes tk codt f Cemdttion true
Symtoc
Cod f Conditiom
debug='
Prlnt
debuq f
Clnus Startemunt fdeby
> tnecut. t h cod t h condtton false
thn wlse ezecuts ebe block od
Smpba revs - .-
. - . . ehe Statemir

wn us X> (fahe)
Put ' l s lenthon 2"
ebe
Puh "z is qreatevthan 2"
end
Resule z s uthan a
wnes Modyterr ondtton oill Ae
wtl ercutty Code 4 thu

falut Gromp van:


van fake
Print1... valu " val
Rualt+ Prmt"à., valuu" nun vari
Ryult . Vauu
Volul
Case statement
o m p a thu eprenier Specytedb Case and czade
th col whun matchu
t exampui- $agt=5
Cose $age
Ohn D... 2
"

Puts ba by "

whun 3 6
Puts "IFtL chttd"
hhun 7-- - D
Puts " cheld

Lobn 1 - - - 18

Contol Statementt -ime


Ezetdtes Same blocK fLod Spe cifeol mo f
LOft%
Th folloroing Certbrol statnunt nuby Cm supports
*Ahih Statemn
*hi Hodter
*until StattmTt
n t i l HodtpleY
for stattma
break staatemm
ncxt Statmrt
Kedo
Redo StatemeM
*Retry Statement

hile statvunti whilh block o£ tool f t i ondltty


enccutes tu

eampt
$Num = 5
ohih 4ie fnum do
Put "ivalut. is
#fi
nd
P í valu is o
valuu is
valu s a
Valu is s
(6
hi Mod r!
T aho Slmlar to uhil statmint but we
aure ort
ttfng Corditi0n at d o block bu no
(harg
loqica lly
i o
num 5
bqin
Pc"i valw s
#fi *
end whil fi
esult iValn is
e
fnun
valu fs
Valu 2
Valu s
lu 4
UntilStatemuntr
T cwtll
Cuecuts th statements ohum ti corditton
falhe
It is vevoe of uhie statemunt

i=o
fmun5 oP
H l qií> fnun do
Ruk valn.
Vvalua g ífs o
ef. i is
# $i" vaulu of 1ÉI
end
i+
wntil Hoditer Value iis s
sinilan
simil
valu o1ír4
T+ un cliondlity of Until
but w an oritinq a tondti on at
statemun
end
block op Stutemat
fi-o
num 5
begin Perult
"
Put valu. 9 i is #
fr" vau, e. i is o

end
wntil fi> /nu valu of i is2
valu eyI
Volus e i
fo atenunts
Codt ncc fo cach
eomevnt in
epres
ent cut cS

variable L, vaviabb. ...J in exprtssian [ elo 7


for
Cocl
emd
for i n -. 5

Reult valu of i s o

Valus. of i is 2
i is 3
valuu o

We au ale havng mi. mor a y


expresien) each do variablh(variabh ..7/

end
lo... 5). each do /7
Puts
end
Break tatement t-
terminates
m%t fnnvn lcop
wit
T amethod oith an
an amoera
amocfa ted slor
ted blotk
Terminate bloc
calhd ath m the
iit s
for itn 0...5 Rult
Valut is o
loveak vauu fss
end Vrlu is 2
'valu is # 2
Putr
encd
teratten
mos6n
Nex 6taturmint thu nent
fumps to tollo uth
luok u r h in
b l oblock
c k {f
iF
ezecuton

teminate
lpop
blot
bloc fo
in
ica
o...5
thon
esulk
valuu s 2
met vau is 3
tnd
Puts valu, is 1 valu is4
Cnd valuu 5
Kedo s l a t r : mestiih toop usiboul
Kestot the ilevatior t th
Cheskirq loop tondition

fo in o...5
Peu

recdo
cnd
thol rl i
t 2 lock,
bloch e rolhi
qY
kety statemun heraton
iterator hun
hm h
Ppcwy nn
retry
Y trtl tnut hfW Slant I apin
todrtion
the
T mans
Deull
from Starting
for in D.. 5 valus. s
Valus.
valut
Pu "valus. is # {7 valu. s o
erd
valuu s

Hebhod Stmilar -lo furnctions în i


Methoos au ve
Clhus p/oqrammlrg ldnquage er or more paluba
a used to bundl
Method
into Stnqlu, untt
statemens ulle
starh LoHh lotor cate
ethad Shoulol
stant£stant wth upercat then ruby Lolll tuah
thab tenntunh
calh'ng o llp
Dllor le
wlse
Methods
Shoulol be dftned beyor
m
mutha
tha vokin7
kivok ing
elepton wndytned
h u

Hethods
mu Starh
colth
cofh dey
aY

[al:defauth]. .[, *ag 1,r


Zyfntar
methodnarn
dy.
df enprosem
sHatemun
melhod
melhod cve Can
w
end Call
call Sinpll
3impll
i when (O
SIple. mtthod method
namu

wdte mly
paoarrttest vohon
w Cal methoo oith
ACCepls
Cun
wrtte met nam alor
melbodl nau alory
ot
Ppometes
olth rammteY
ethodname (ao, 30)
dey n
Cnd
Set letault valuus h formal
e eed +o amign he valuu for
aquminby in methd
kuby Vana
"Per")
def
=

mthad- namt va I=
def ,

Pus "t fvar


Ad Pub "#Va" Reul
Crd
t t "c", " " Kuby, Perl
test
Ketwm statement n ruby ea
t0
to r
reew
trm
m o

Ketwn Statment
metiod

ore vahus frm


rtturn ep 1, tpr--)rctwm arl
tkn the
than tw taprensíms

Valu Stord im ray vastalb o


# i ll r
will reettw
n NEL
NtL
Czpmssien e t w n
thn
I7 no

dt tat
00 sult
DO
200
K900 900
TCtiom i,3,E
end
valtest
val
Put
Vani abl anumettsi
method i a t takes too
declad a
Suppose we
Paamters iOhs) e ve uwe all t A metha , Lwe need
to Pan wo panamES along oith PE
"mthols that worts
to duclart
allous
Rubq vaslabluk
Lo

Coith
0: 0 panomttrs.
d g . Sampl( tee)
PLebs "no.4 param t/ tat, ungth?
for
f or n 0... . test. enrth
Puh #test [17
E n o l n d

Sampl "", Ruma


3ampts " "Lakshmí,'AP"

Rame
ne Param 3

lakshm
AP
valu. n t o Simgt vaiahe
ATT O Store
stort mor than en

from0 to
T-1
ray tnde will Stav
no megativ
mol
m
amy,
Creatien o Arays a y s to create avnay
toC a havtng So mam
neo
method
B 4 using ,neuw
ramis = array
with 9i aroy.
ary
By ing. nqo me thad
ame aray neo[so) tKa valuy.
Can
bnserr
Ab mte locatton

wth valus
mthol
New La kshmi ven Ky, a
mamls ATray. n uw[ h, kana
ttore 4rst Qrgiimmt rpreuik t t Siu ef array an
followe d by ay elnents
t h valu
4 neuo mutuwad S/u
2* 2
valus r aray newlib)/l
o to q valus and k
cotll taka Vnliuu from
vaniab4
isetid into array
Sayua al.
mebhod
Gy wsing Bul lt-ím
nama Array ]1a,9,)
nanis a,
ray 3,4
Tams =
a r ay lo, --. 4)
v l a bl rtm
AL axu fo" Soring amay va mto

b
tlbmet aray.
7 9 i v e flrs
Sepntae array. frst
last aray:katt
m
w i l gime l t t elornnt array.
length > a r a y . ungth.
ar
tha Siu e
coitleoitl give
Siu
> aray
Sie
síu arra
wlUoll qtve
5aflndea) army.at(inde)
7 w qit a freula Fndez. totation valu
)atlete at(tnder) a array. dlita-at limde)
-

w i l l ddete a p a r i culan fndslocation


Vnlu frem aray.
clear% w iw i
aayclear
Clean all he valuus aray

SConcaf-/array) > array. toncab(avmy) înto Singu


Il Cembivik ho0 ray vauy
T
aray
Push> aray. puhl)
the
elurnur imtio
imtv aray
i l l
sert

rivevre
o) reveese rray
th ay elumunt
T w i l l evose

) Sor aray.Sort, s elamunts basd


bad
coeatku aray
w
Ato iiIt OUE
en ahabet

HashesS
is ale calluol a mocia tivc amay
T us Collectien key vnlu przirs i e
errploye'> "Salary
T Stnlan to aTras txceph tt inolun t
Via arbitary ky 4 an e b e yAe t an
den
imttgn ndie
te elmens m hash s cthus ky or ml
ravoue
an
imertten ordo enists t t
mo
e Scanch y ik w no

we
oltl retun NTZ

Creatien Hash ncw


ney

W an
CrLate an empty hash usfng
by wain4
mthod menth Hash in ew
GA dgau lk
valuts for hashs
Hash. haw l "mvmth ")
mon lhu
*
menths = tHash. new "mønth
tn ha hat
*nat has dyault D
Now,
Now, ve an acen amy Ay actossirng thu hash
Valu If Kiy or vnlu doctnt Cxfst ,
value
willrctwn" defau tt
Puts "#fmenths [o]f
Put month 7o] *
w . an also Crate hashy as tollos yvalus patr
H Hash"a " 10, "b" o]
Ha Hash f:a 10, :b a0f
tH :a, 10, :b, 2o

months Hash neu l" mobth ")


months =fa " 1o, "b"20f
Ky men th Ky Resul
Pu # Sku b

unctia Peyorrm Hashes

.hash.Kuys euls ted


w i l l qveg t in
kys COhich au

hash
l cisted
2 hash . valuu b valluy, cohtch
wohtch

wiU qiv
in hash
33 hash c l e a
all the elmenh m hash
will clean

4hash.deletelky) fom hash


I otll reove yvaluu pair
5hash.
T
has -valut
otll
?(valu)
chck valu is exietol m hash or rE

6 hash hos-ky (value) enfstecd Fnhas rot


oltlcheck Ky
hash. empty
wilcheck hash us
Cmpty notnot
S
Shash lumgth
w l etum rgth e hosh
hash Sert cloment
imhashs baseyt on
Sort the

hash . éach Tkey, valu,| block }


uu tes tol
a totha Prin& Fy valu Pairs
pairt
H
Pruná n h a s h

T teators
Ttmators
u alo
.types
eg ualent
F t e r a te s
Hmi
to
in.uby Loepsp
loeps
by
Lw
oe ad hautng rc fteratos
Emumerahl abfec
3 Custom fterators
r t r a to%
the follouwing terator
ferators

Mumeic
Tteger cla dejines
Cpto

imy u m b e r s

Fterator
i t e a t o r

poin step
tloatiry upto tte mmbr

wil piná
-
z ntegerpto ( itege)
Synta j
eepiols) lal prnt
44 Statemernt
t5, 6 r c p e a e d ly Primá
imts o
o fill
l

statemm
no. 1 n t a r s mteger t i m a
qiven
given

3 timeu "thlo
Heltb Hello Hello

skep- wil nerase the valee Step by Step

pto ths vals


vae
0. step
math: Pr, D.1 ) S11 put z}
# Prin fem t o 3.14 cach steP increment
by 0u
Enumembll hicrts hash and mnges
tutced for aay,
Generally time
wil taki tta valus every
each zt

Y to tatiny NTL
8,3].cach 1/>/ prnt
c cach 1x/ print
(13).
K ucqaerf tO tpto(3)
a l i o used for o clan
FR open fthnamt) do lfl
f. cach { / tnel print linef
Cnd
cah line in f i l
4prn
ncec;
Cah- oith
-

uoith
o Yth fmdec
ndec.
ne alog
Lprint

er
each chon timc ttwitl tak only
LCach
Chara e t v

3Cuctom terators: Ow own


o wn itera
teratterrs
ors
CamCreate
we
def twice
t. rld
Yetld

Jetld
Cnd
blocks which are

yetd sed call t to

eisted in ruby Pgra


E tprtso)-
Matchig (o) yular Etrtuiorns
Pattern
atern
s tth
s
aa Special sequene
Special Sequene
ovfnd oil
oid
Cpres/en

A Tequla. tth orind


you ma
a

tha hetps iO
chac h a r a t e s Sypiar
5tt Stirgs uing speciaduol Star
String o
folowec by mttern attewn
patten
ltterals tis a
ezprsíen
A g u lar. r
betwcen slashau (ov) dlimitd folloued by
Pattern
/prattern/ im

Kegeap Lttraly - daltniter ccauue it


Closinq Slash u not a -truc additoral
Centains optional flag , that Contairi
mformatlpn ucriptton
Modiyier Cau whn matth test
iqnore
matchal agains
t o be
fattern trcat nu
mubttlene tect, SD
ordiaxy Char it
line a
m e u kine
allons too math
allow h t e spaca
trtondso. Sign
m gula
nd commurn
exprenen

folowg Reb
Rub epteady
Opetoraly
teeb ni
match
/Ruby ?/ hes or

teet
follecod y
match

Riuby optional m
muub
t ill
liin e
e

wnicoele
uníeook
c h a in
cha tm
m a t c h u

//mu >
moode

mathu s r slarh
r/1/3 back slash
back slash
Hatehu sing
/11
i-
tacdony
Methal
kgex Can alo
Crate enP twith

rg ep.
new
) k i g exp. tomptl

Kanpl

egep. Tmtu("euby?)> equivaborto |Ruby?7


2
Rgep-ua("yuby ? Reg tapi: 1qrorvtca se) /rk4 ?}
"

»
3
Regenp. unton ("Raby", "perl", "phython,/Java( Sep):7)
LT will Scanch for mo
than eru partberns 9
a timne

L wll Seanch for 5 uwordh


Python, jala, Jaa Seripe
Cuby Perl,
keg eap Synkar? oriten behoun slassy
1literal ha drtct charg
rubyl > matehu ru
Chan clanet
o ry
/lR]uby/ Ruby
o rube
rub Lye1/2 eby vouwe
case
lower
Tmatchy
laciou7/> louwer casc voweb
Caclou]/> matchs u

Speuial chanacter clame


ncuoltne

1./9 maths ecept


mod
multiline
matthu
/m
matckus lg'b-
ttu
/td/>
matchu eucept dtge
/1D/>
4 RepeLtiom
s oplional
ruby ?/ 2

3 j*"
1 d 3 / Caty
ver dus al
Ocb apllcatton fumrk
aa highu Hltert
otl davte tamn
davtotamsen
And t t wa Cori tten n ruboy by
S
So t l s alo non a
Ruby en ails
A maimly ( toil, Véeu0,
Cortro llor prler»
s e Mvc to
tvols tuat aru rauir ol
Providi almost all t
butld
build a web appltcatton e divtdad tnto
Cm
prcen
Thu Softuwt dvelopmeT
three em virom munt
evelopmurt

Testing
3: produltton
erfom vious
s e d to
to
emvironmimt
esed
These
variow puopose-
tas for
featwa kalki
Ata prgamming

Actve Record coraton

over
conflg
C e n v m e e r n

4 SCalf holding
Gut4 n terttng

e t a pregromning wrttinq4 proqrmm


proqrom
cMes f wrting
Pregrommtng
Heta Cooling for genvratiry
coorá ue ong
ongh
o t h rami
Proaromy.
progrqm hamdu thuy
to make d a t a to
to uttla me
A Strat9as
Preqrann
mpub s callhd
calla.
meba preqramming
mEta
p7 qrmninq
automatieallg
gnodtfy
Acttve eazd
Pal in troduced Cerncepe aCtve
rami oTk collmns in da-ta.base
Bto ton tt4 the
Schoma
Cnvention over Cenftawratten
etc
stth a Net, Java,
Conpg wratton tode
thn ramt OOTks
lot to to
TEquire to toritt
a
wrdba
C o n w r t t b n a

con

on
ais aming

Whe
eolue
as
qub rubb
th iorttng
arge C o n f í gw n a t t o n

Cmate a tnporary

holdang hat
C o p e r u n

Somm timu developvy major techmi9


how
cOorknga n d u
Observe
Code to Looktngand
au

e uCode
n the n Staf holdlng

Testing
- tooh n
utlt en n tettng c z c c t e
C 2 L c o t e

buit L
w or
riitt
e e z

fos a

test co
thu
h L
maky
a S t m p l m a m n e r

You might also like