You are on page 1of 35

Ruby Object Oriented Programming Language

Table of Contents 1.0 Abstract 2.0 Introduction 2.1 The Ruby way of Programming 2.2 istory 2.! Object Primer 2." #etting Ac$uainted with a Ruby Program !.0 The Ruby Language !.1 The Ruby Language at a #%ance !.2 Object Oriented Ruby !.! &ontainers' Iterators and (%oc)s !." *tandard Ty+es !., -.+ressions !./ 0odu%es ".0 1sing Ruby ,.0 Ruby as a &ase Language for &*& !2, /.0 &onc%usion 2.0 A++endi. I3 (ib%iogra+hy

1.0 Abstract -ach +rogramming %anguage +resents a +articu%ar wor%d 4iew in the features it a%%ows' su++orts' and forbids. In this +a+er' we stri4e to +icture the wor%d 4iew +resented to the +rogrammers by Ruby' a +ure%y object oriented scri+ting %anguage. (eing a com+arati4e%y new %anguage' Ruby shares the ease of use with Python' com+actness and +rocessing abi%ity of Per%' object orientation of *ma%%ta%)' and +attern g%ueyness of -iffe%. 5e start of with an introduction to the %anguage as we%% as the object oriented +aradigm' then systematica%%y we treat the synta.' usage and +hi%oso+hy of the %anguage' res+ecti4e%y. Our objecti4e is to introduce the %anguage and its ama6ing 4iews to the +rogrammers and ad4ocate its usage' at times justifying the c%aims made by the Ruby +rogrammers wor%dwide. This +a+er can a%so be thought of as a tutoria% as the third section of this +a+er teaches its reader the ways and words of the %anguage in a to+ down a++roach whi%e the fo%%owing section strengthens it with touching more sensiti4e regions of the %anguage. 7ina%%y' the +hi%oso+hy of the %anguage is +resented since getting ac$uainted with the +hi%oso+hy' +atterns and sty%e of the +rogramming %anguage ma)es anyone more in8%ine with that %anguage and its +rogrammers. 2.0 Introduction “Man is driven to create; I know I really love to create things. And while I'm not good at painting, drawing, or music, I can write software.” !ukihiro Matsumoto' a.).a. ""Mat#'' 9!: One man;s +assion for creati4ity has gi4en birth to a %anguage that changed one;s %oo) towards +rogramming in who%e. A%though re%ati4e%y under8used com+ared to those of Python 9,: and Per%' Ruby offers a more comfortab%e en4ironment to its +rogrammers. It embraces the best features from %anguages that are best for those features' and yet is ama6ing%y sim+%e and free of com+%e.ities or criticism e4en the best %anguages aren;t e.em+ted from. In this 4ery first section of this +a+er' we wou%d %i)e to introduce this e.citing %anguage' its history' as we%% as a treatment of the +aradigm which is the heart of Ruby Programming8 Object Oriented Programming. (efore jum+ing to the ne.t section' we show how to insta%%' code and run a bare8bone ruby +rogram. 2.1 Why Ruby: The Ruby way of Progra ing There is a good number of +rogramming %anguages around< on%y a few are in the e4o)ed sense of an enthusiast' name%y8 &=&>>' ?a4a' Per%' and +erha+s Python. There are se4era% reasons for different %anguages to co8e.ist des+ite an immediate yet mis%eading conce+tion that one uni4ersa% %anguage wou%d ma)e the %ife of +rogrammers more harmonious. The first reason wou%d be the +aradigm many +rogramming %anguages use' different +aradigms that are +erfect for different +rob%ems arisen. Prob%em A may be too sim+%e for Object Orientation to +%ay' Prob%em ( may ca%% for some 7unctiona% he%+' and using any %anguage other than and Object Oriented one may be a +rogrammer;s attem+t of suicide for Prob%em &. There goes the first reason why different +rogramming %anguages e.ist. Po%itics can be another reason. After a%%' it;s the

2

cor+orate war that started the batt%e amongst the +rogrammers in the form of .@-T 4s ?a4a. Another reason cou%d be a +rogrammer;s +ersona% affection towards the %anguage as we%% as hisAher +sycho%ogy. To a non8+rogrammer' this may seem a subt%e reason but it is one reason a %ot of +rogramming %anguages are sti%% around. *ome +rogrammer;s menta% framewor) may be so%e%y o4er%a++ed with that of 7unctiona% Programming +aradigm whi%e other may be aficionados of the object oriented +aradigm. The reason this %anguage8 +rogrammer issue is raised here is to justify our reasons for ad4ocating the justification of another %anguage Ruby' whi%e titans %i)e ?a4a' &>> or centurions %i)e Per%APython a%ready e.ists. Ruby;s +rimary +ur+ose was to inc%ude the best features of different %anguages whi%e ma)ing that integration sim+%e and hiding the different com+%e.ities from the +rogrammer. 7or e.am+%e' it is tight%y integrated to the under%ying o+erating system as Per% is. It is sim+%e to use as +ython. And' the best +art about it' is that it is as +ure an object oriented %anguage as *ma%%ta%) or -iffe% is' on%y without the hard8to8 understand re+utation. The features embedded in Ruby are enough for it to emerge successfu%%y as a dominant %anguage in its own domain' which is e$ua% to that of Per%APython. Anything that can be done with Per% or Python can be done with Ruby' much c%ean%y and with sa4ing a %ot of +rogrammer time. 2.2 !istory “$ell, %u&y was &orn on 'e&ruary () *++,. I was talking with my colleague a&out the possi&ility of an o&-ect oriented scripting language. I knew .erl /.erl), not .erl01, &ut I didn2t like it really, &ecause it had smell of toy language /it still has1. 3he o&-ect oriented scripting language seemed very promising43hen, I reorgani#ed the features of .erl into a class li&rary, and implemented them. I posted %u&y 5.+0 to the 6apanese domestic newsgroups in 7ec. *++0. ” Bu)ihiro 0atsumoto, a.k.a. CC0at6DD 9": Bu)ihiro 0atsumoto' or E0at6'E as he is )nown on%ine' is the creator of the Ruby +rogramming %anguage. Ruby is an object8oriented %anguage suitab%e for writing day to day scri+ts as we%% as fu%%8sca%e a++%ications. 0at6 began wor) on Ruby bac) in 1FF!' because he wanted a %anguage that made him +roducti4e whi%e being fun to use. Initia%%y +o+u%ar in ?a+an' Ruby has been finding its way into the hearts of +rogrammers a%% o4er the wor%d. According to some' Ruby is more +o+u%ar than Python in ?a+an. As he says about his creation of the %anguage3 “8hortly after I was introduced to computers, I &ecame interested in programming languages. I &elieved that an ideal programming language must &e attaina&le, and I wanted to &e the designer of it. 9ater, after gaining some e:perience, I reali#ed that this kind of ideal, all purpose language might &e more difficult than I had thought. ;ut I was still hoping to design a language that would work for most of the -o&s I did everyday. 3hat was my dream as a student.” <,=

!

 Ruby is de4e%o+ed under Linu. clarified the am&iguous &ehavior of the language. read thousands of lines of source code. *1*.ce+t a few web8centric ones where we used Linu.F. It runs under 1@IL' IO*' 5indows F. wrote uncounta&le test scripts and e mails. and finally compiled this great &ook.s birthstone.+erienced' he %i4ed his dream and de4e%o+ed Ruby. 3hey researched it.= (e%ow are some facts about the Ruby %anguage3  0at6 is the hand%e Bu)ihiro 0atsumoto uses in his documents and mai%ing %ists  Officia%%y' the %anguage is ca%%ed JRubyK' and historica%%y it is ca%%ed JrubyK. found &ugs /and even fi:ed some of them1. 5hen he became more e. 7or that' Bu)ihiro 0atsumoto is than)s the Ruby community8 “3hey &ecame interested in a lesser known language from the 'ar >ast.' and is written in fair%y straightforward &.2' the first 4ersion was 0.AFMA@TA2000' 0ac O* L' (eO*' Amiga' Acorn Risc O*' and O*A2.1. 0oreo4er' 0at6 +referred writing codes to writing documentation' which near%y doomed the %anguage.s creator to attem+t a new %anguage in the first +%ace was +erfect object orientation. 2. %u&y is certainly well documented now?” <.F. It is o)ay to use both of them but ne4er R1(B.  Inf%uenced by Per%' 0at6 wanted to use a jewe% name for his new %anguage' so he named Ruby after a co%%eague. Ia4e Thomas and Andy unt 9PRA#0ATI&: are two of the American Ruby enthusiasts for whom (ang%adeshi student %i)e ourse%4es ha4e enough information to write a +a+er such as this in Ruby. The initia% res+onse to Ruby was not 4ery +retty' because most of the documentation thereof were in ?a+anese' and therefore the domain of Ruby were %imited in ?a+an and ?a+anese s+ea)ing +rogrammers on%y.s s+read beyond far8east.t ta)e time for it to go in the same trac) as the big guns %i)e Python and Per%." #b$ect Pri er One of the factors that moti4ated Ruby.M.  The current 4ersion of Ruby is 1. In this +a+er' we used the %atest 4ersion of Ruby' most of the codes were de4e%o+ed under the 5indows LP +%atform e. It is forecasted by some enthusiast Gto others they are o4er86ea%ousH that Ruby is enough to re+%ace Per%. If c%ean%iness was the on%y factor' Python was a%ready a4ai%ab%e. Bu)ihiro 0atsumoto had dreamed a " . The beautifu% %anguage as Ruby is' it didn.After using 4arious too%s and %anguages %i)e Python and Per%' 0at6 decided to create a %anguage of his own which wou%d be +rettier than Per% and more object oriented than Python. owe4er' a c%an of +rogramming enthusiasts who became interested in this %ess )nown yet +romising %anguage from the far8east came a%ong and wrote some documentation and boo)s on the %anguage.

Programming has a%ways been re+resentation of a so%ution to a +rob%em in an a%gorithmic a++roach. The fi4e conce+ts are gi4en be%ow8 .+%ained in the necessary sections.s a++roach in the +aradigm.ists' something that has some attributes' something that can show some beha4ior.e. 5ho%e courses and +%ethora of boo)s ha4e been de4oted to treat that to+ic.s +oint of 4iew' the so%ution becomes c%earer and the a++roach towards it becomes faster if the %anguage gi4es the feature of simu%ating the b%oc)s of the so%ution in the format of the associated b%oc)s in rea% %ife. In a more %ay term' an object is sim+%y as it.+rogramming %anguage which wou%d be object oriented enough to ma)e a +ython +rogrammer jea%ous and *ma%%ta%)ers ta%) high about' and as a fruit of his dream' we are +resented with Ruby. *omething that e.s the reason object orientation is the dominant +rogramming +aradigm when it comes to creating robust time critica% Gor any other a++%ication for that matterH a++%ications.+ect the co%or of the students eyes to be in+uttab%e for the +rogram' it. That. a%ong with the same set Gor the necessary set' one can. In this section' a brief +rimer to the object oriented +aradigm is inc%uded' on%y enough for gras+ing the terms intuiti4e%y as the references arise. 7unctions +%ay the ro%e of sub8jobs which acts as bui%ding b%oc)s towards the so%ution.s described in the %e. And hence' no +a+er in Ruby wou%d be com+%ete without a forma% introduction to the ama6ing and +er4asi4e wor%d of object techno%ogy. owe4er' from a +rogrammer. According to some e. In this section' no %anguage s+ecific issues or syntactic sugars sha%% be raised' those are sa4ed for %ater use. instructors' students' courses etc. . 7or e.s not necessary' and is ca%%ed abstractionH' then the +rob%em is ha%f so%4ed in the +enci% and +a+er.+erts' a mode% to be $ua%ified as an object mode% in the OO wor%d re$uires fi4e under%ying conce+ts8 which are' objects' messages' c%asses' inheritance' and +o%ymor+hism.am+%e' if we are to ma)e an on%ine registration software' then if the de4e%o+ment en4ironment enab%es us to treat different +arts of our so%ution to mimic the characteristics of the rea% time actors of the +%ay' i. To +ut it sim+%y' an object is an atomic entity' formed from the union of state and beha4ior.t e. That goes the %ay man. It +ro4ides an enca+su%ation re%ationshi+ that ensures a strong interna% cohesion' and a wea) cou+%ing with the outside. In this section' on%y the re%e4ant of it sha%% be touched and the other to+ics sha%% be gradua%%y e.icon' informa%%y we may ca%% it sim+%y' a thing. The first thing in order is a definition of an object. An object re4ea%s its true ro%e and res+onsibi%ity when' by sending messages' it becomes +art of a communication scenario 92:. There is much more to object orientated +aradigm to that.

am+%e' a b%ue 0a6da 0iyata may ha4e the attribute set Gco%or' mode%' sub8mode%H associated with the state set Gb%ue' 0a6da' 0iyataH' whi%e being ca%%ed a Ocar. In a +ure object oriented en4ironment' e4erything is an object' e4ery ty+es' standard' containers' aggregates and what not' sha%% be objects' dis+%aying certain beha4iors' ha4ing certain attributes. 0athematica%%y8 Object N *tate > (eha4ior The state of an object means the attributes that object has' for e. 1 Any reference on @7* 1nderground 2 is made by 0afinar Rashid Phan. It may show beha4iors %i)e' acce%erate' bra)e and tight turn. 5e must be ab%e to send defined messages to them and recei4e feedbac) from them. They must ha4e their +ri4acy and +ub%icity. (eha4iors are ca%%ed methods in many %anguage terms. It is one of my current obsessions 888 0afinar R Phan / . object. (y the way' the e. In a more forma% way to s+ea)' we can say that an object com+rises of states and beha4iors. #b$ect The +aradigm itse%f is named as Object Oriented Programming' and +utting the conce+t of objects in the front seat does a %ot more than justice to the nomenc%ature.am+%e of 0a6da 0iyata is ins+ired by the game we recent%y +%ayed' @7* 1nderground 21.

The conce+t of c%ass is to sa4e us from that di%emma. 7or e. Or' the beha4ior shou%d be in4o)ed to that object. @ow' what ha++ens to the +%ayer in the object wor%d is' the message Omo4e. (ut to +erfect%y interact in an interacti4e scenario' one object must send a message to another object. It is an interre%ationshi+ among c%asses which sums u+ to something %i)e this8   2 . And a c%ass may a%so ha4e its own ty+e as an attribute. Class *o far we ha4e on%y described objects' entities with beha4iors and attributes' and our e. 0oreo4er' a c%ass may contain other c%asses' such as the Race c%ass ha4ing a who%e set or &ar c%ass as +artici+ants. &%asses are what ma)es the word abstraction associated with the object oriented conce+t.+%anation of the messages wou%d be %eft for the more Ruby re%e4ant sections.s car shou%d acce%erate' and it shou%d mo4e forward. It shows the beha4iors bra)e' dece%erate and acce%erate. On o+ening the game' we ha4e a city where different cars roam about' the +%ayer. (ut what are our 0iyata and -c%i+seR They are cars' or more accurate%y' 4irtua% cars suited for the game @7*1 2' not the cars from @7* ot +ursuit or from #TA III or 0idnight &%ub 2. is +assed to the car which ignites the beha4ior of mo4ement in it. as we%% as the beha4iors name%y turn %eft' turn right' co%%ide etc. Our e. &%ass is the coo)ie cutter where the objects are the coo)ies. Inheritance 5e ha4e discussed c%asses' messages and objects' and inheritance is a sweet Gand con4enientH addition to the object oriented +aradigm. *uch as a Person c%ass may ha4e another Person c%ass in the form of s+ouse.am+%e fina%e of this section wou%d sim+%ify the conce+t further but in this bare bone introduction of the Object' the e. &%asses act %i)e a tem+%ate.s now thin) of the 4irtua% wor%d of @7* 1nderground 2.am+%es were 0iyata and -c%i+se. *o when we say &ar A is a car object' then it must ha4e a%% those attributes fi%%ed and beha4iors shown.s ca%%ed message. *u++ose' the +%ayer +resses the 1+ direction )ey of hisAher )eyboard that shou%d mean the +%ayer.s car is to find the different s+ot and start off with a race. And that is what.am+%e' the abstract car has the attribute' co%ors' mode% and to+ s+eed. In another scenario' if my 0a6da 0iyata co%%ides with the 0itsubishi -c%i+se of the AI dri4en o++onent' then a third +erson Gan obser4erH may say Gin %ay termsH that J0iyata hit -c%i+seQQQK' or in Object tongue' it can be re+resented that the co%%ision message is +assed to the en4ironment object with 0iyata and -c%i+se as the +arameter. %essage Let. A car may ha4e the attributes mode%s' to+ s+eed etc. *o' if objects were the on%y objects in object oriented techno%ogy' then the who%e +aradigm wou%d scare its +rogrammers off because e4ery time a new car is to be instantiated' then the who%e definition wou%d ha4e to be generated.

owe4er' there are certain issues bound to it which ma)es a +erfect com+%etion to the conce+t. *ame beha4ior name' dis+%aying difference in different chi%dren is the main theme for +o%ymor+hism.t need it. 5ith +o%ymor+hism' the +rogrammer is sa4ed from determining the correct action for the correct beha4ior name for a +articu%ar subc%ass. ence we can say' the 4iew of the car is a +ub%ic attribute whereas the 4ariab%es that determine the magnitude of damage is the +ri4ate.am+%e' there are si.4e been had inheritance not be there. Re%ating to the set conce+t' we can say that c%ass ( becomes the su+erset of c%ass A. other c%asses as the names abo4e' then our coding wou%d be one si.  Poly or&his Po%ymor+hism means ha4ing many forms. 7or e. There are many other +%aces they a%% differ from.act%y +ub%ic because +ri4ate attributes can be M . It fo%%ows immediate%y after the conce+t of inheritance. 7rom inheritance' we ha4e e.em+%ified the racing scenario. (ut other attributes such as the array of bum+ history recei4ed by the car from the en4ironment due to ca%cu%ate the damage attribute is in4isib%e' because we sim+%y don. 7or instance' the co%or of a car may be 4isib%e to the +%ayer.s the conce+tQ (ac) to our @7*1 II e. *ince a Irift is a race' then it has e4erything a race may ha4e and something more' and with inheritance' we don.am+%e' the car getting finishing the fina% %a+ first wou%d be dec%ared 4ictorious in a *+rint or &ircuit race' whereas the car gaining ma. *u++ose the su+er c%ass Race has a beha4ior ca%%ed 4ictory. &ircuits ha4e a %a+ more than 1' *+rints ha4e on%y a sing%e %a+' 1RL is in a stadium rather than street' in Irag' the gear is a%ways manua%' in Irift the more angu%ar bra)e gi4es the +oint. The first of them is the access contro%.imum +oints wou%d be the 4ictor in the Irift race. It refers to the fact that some attributes of an object shou%d be in4isib%e from the other. (ut' most ob4ious%y not the same ru%e for 4ictory a++%ies to a%% of them. *ince the other si.ica% that the chi%d inherits from the +arent and ends u+ with more than its +arent' but that.th of what it cou%d. ere we need to use it again. Again' we cannot guarantee what is e. If we aggregate a%% those common ru%es and boi% it u+ as a su+er c%ass race' and dec%are si. A %itt%e +arado.Jif c%ass A is inherited by c%ass (' then c%ass ( is e4erything Gor has e4erythingH c%ass A is Gor hasH and moreK.t need to re+eat things. ty+es of races' name%y' &ircuit' *+rint' 1RL' *treet L' Irag and Irift. owe4er' in one case they a%% are the same' they ha4e +artici+ants' en4ironments' winner' runners8u+' %osers' co%%isions and others. To some Object +urists' Access contro%' or enca+su%ation is one of the main +i%%ars of Object Oriented +aradigm. A%% we might see is the change of the cars sha+e to a +athetic form once damage has been recei4ed. c%asses are deri4ed from it' a%% of them wou%d ha4e the same beha4ior. The fi4e com+onents stated abo4e are theoretica%%y the main +i%%ars of the Object +aradigm.

readab%e' writeab%e or readAwritab%e 4ia +ro+erties or accessor methods.am+%e' the ha6ards and constraints in a racing en4ironment may wait fore4er for a car to co%%ide' thus' +rogrammatica%%y they may be im+%emented by an infinite %oo+ and obser4e. The ruby code for it goes %i)e this8 Code 1: Hello World [hello.rb] #!/usr/bin/ruby #begins . *imi%ar%y' in a windows en4ironment' the button may wait fore4er to recei4e user in+ut. . Another im+ortant theme in Object conce+t is Iesign Pattern. This is a sma%% section in which we de+ict a bare8bone Ruby +rogram' fo%%owed by the ways to run it.hausti4e sections on definitions' history and to+ica% +rimers' this section starts off with the %anguage itse%f. It is customary to ha4e a%% the attributes of a c%ass +ri4ate and %et the accessors +%ay the )ey ro%e in readingAwriting. Thus' this introductory section on Object Oriented +aradigm ends. In Ruby' Patterns +%ay a 4ery im+ortant ro%e and a who%e section is dedicated to the conce+t. ?a4a a%so has the abi%ity of ada+ting design +atterns though its not mandatory. There is an in4isib%e simi%arity in the way different objects such as themse%4es communicate with other objects and can be +ac)ed to a same +attern to ma)e a +rogrammer more intuiti4e in his $uest for abstraction. A%though it is not a )ey term herein' but to be a good +%ayer in the game' one has to understand the conce+t of +atterns. And as +romised' we +ut no syntactic annoyance' not yet to say the %east. The conce+t is immorta%i6ed by +ure object oriented %anguages %i)e *0ALLTALP' (-TA' -iffe% and Ruby. In fo%%owing set of sections' more ORuby8centric. . 7or e. 7or now' a%% that is necessary for us to )now that design +attern refers to the recurring beha4ior se4era% object shows though themse%4es being different. 2. The who%e *wing %ibrary in ?a4a embraces the 0S& G0ode% Siew &ontro%%erH architecture which is a core of design +atterns. definition and im+%ementation of those conce+ts wi%% be e%aborated as necessary. As customary for the first +rogram in reference to a +rogramming %anguage' we wou%d start off with the J e%%o 5or%dK +rogram here. print “Hello World!!!” #prints Hello World!!! #done output: Hello World F . (y the way' such a +attern is coined as the JObser4er PatternK.' (etting Ac)uainted with a Ruby Progra After rather e.

rb shou%d do the tric). The fo%%owing are some noted +oints one has to ha4e in mind whi%e running a Ruby +rogram3  In the 1@IL en4ironment' if we being our code with the magica% TQ' for e.istence of Ruby.t section' we start our endea4or to describe the Ruby %anguage with a%% its beauty and g%amour. 5ith that fact in mind' from the ne. ".es to be it.am+%e TQAbinAruby where AbinAruby is the directory where the Ruby inter+reter is stored' then just changing the +ermission to e. In this section' a crash course of Ruby sha%% be +resented. owe4er' there are different way so run the +rogram.r&H. Another way to run a +rogram is to in4o)e the Ruby inter+reter Gty+ing ru&y myprog. The synta. of the %anguage is easy enough to be gras+ed in a wee). @o main method' no starting or ending +arenthesis' nothing e%se. Ruby is an inter+reted scri+ting %anguage which is fu%%y object oriented.0 The Ruby *anguage After a rigorous treatment of introductory conce+tion' we start our journey towards the Ruby +rogramming %anguage from this section on. +ractice.tension .ecutab%e Gchmod @: myprog. This goes for any o+erating system as %ong as the en4ironmenta% 4ariab%e G0icrosoft 5indowsH or the bin +ath G1@ILH is set correct%y. It is usefu% for sma%% g%ue +rograms Gmuch %i)e +ython she%%H. (ut the more detai%ed +art wi%% be %eft off for %ater sections. O4er there' immediate resu%ts can be seen after e4ery command is entered' much %i)e the she%%. Otherwise' the +rogram has to be sa4ed in the ArubyAbin +ath or in4o)ed with the fu%%y $ua%ified +ath.s it. *ome may +refere to start from Object Orientation for a %anguage %i)e Ruby' whi%e others may choose the basic synta.Amy+org. 5e wou%d %i)e to choose both at the same time. and shares the com+actness of Per% and sim+%icity and c%ean%iness of Python' not to mention the theoretica% +urity of -iffe%.rb Gthough not mandatory for 1@IL' but high%y recommendedH.em+%ified' scores of others wi%% fo%%ow here from. *o far on%y one code ha4e been e.s succefu%%y done' sim+%y' . 0ost as+ects therein wi%% be touched and described. It has a 4ery sim+%e' no nonsense synta. 7un has been one of the )ey e%ements which instigated the e.  Ruby +rograms ha4e the e.s time and some of the harder conce+ts therein can be understood with few days. 10 .  Ruby is shi++ed with an interacti4e en4ironment' the IR(.r&H.1 The Ruby *anguage at a (lance There is not no +erfect starting +oint for describing a +rogramming %anguage. ?ust one %ine does the job.And that. If that. ".

s su++ose we are creating a new instance of the &ar object whereas &ar is an a%ready defined c%ass. 7or instance8 Class#ame.trum+etG12!H -.id' your&ar.new( )#a no-arg onstru tor yourCar = Car.new( onstru tor$rguments) Class#ame. The first issue to be discussed 11 . Object instantiation is done Ruby with ca%%ing the constructor. lass*ariable #or stati The ones abo4e were just sim+%e toy c%asses' in rea% +rogramming' the user8 defined object or bui%t8in or %ibrary objects can be mani+u%ated the e. 5e )now the II of the object by ca%%ing the id attribute of that object' i.e.act%y %i)e ?a4aA&>>' the dot o+erator is used as accessing o+erator of a c%ass or object. lass%et"od( argument&ist) #or stati instan e#ame. 5ithin each c%ass' we can define instance methods.instan e%et"od( argument'list ) ( = instan e#ame. -. *o we wou%d code8 myCar = Car.' reminiscent of Per%APython. &omments are fo%%owed by a +ound sign' OT. These instance methods in turn ha4e access to the objectDs instance 4ariab%es' and hence to the objectDs state.new( “ma!da” )#wit" arguments In the first %ine of code' my&ar is instantiated with a no argument constructor whereas on the second %ine' the 4ariab%e Jma6daK is fed to the constructor as an argument to +o+u%ate the fie%d.am+%es thereof.)ield y = lass#ame.times. -ach method is a chun) of functiona%ity which may be ca%%ed from within the c%ass and from outside. 7or e. In Ruby' a uni$ue object II is assigned to each object created.act same manner8 “%a)inar”.id etc.abs #output+ 0120 As we can see' numbers' which are +rimiti4e ty+es in ?a4aA&>>' are treated as fu%% f%edged objects in Ruby Gas ins+ired from *ma%%ta%)H. Lea4ing object orientation a%one ti%% a %ater section' it is time we +resent some more not8so8one8%ine code e.am+%e' %et.The first thing to notice here is that since Ruby is an object oriented +rogramming %anguage' the techni$ue for dea%ing with object is what needs to be dea%t with first. 7or e.am+%e' if we ha4e dumbo as an object for the c%ass -%e+hant' which has a method ca%%ed trum+et that ta)es an argument on the decibe% of sound' we can code8 dumbo.lengt" #output+ .print “wow”/ #output+ wowwowwow -0120. my&ar.

7or e. ?ust %i)e we don. The TU V o+erator can a%so be used %i)e the e4a% function Gin Per%H that e4a%uates e.name/!” return result end puts say3oodnig"t(4%a)inar4) puts say3oodnig"t 48ulo94 Output: 3oodnig"t5 %a)inar We will miss you %a)inar! 3oodnig"t 8ulo9 We will miss you 8ulo9! Indentation doesn. The synta.t re$uired either.t ha4e any im+act in the b%oc)ing or sco+e as in +ython' but it is high%y recommended. In Ruby' e4ery b%oc) is ended with the Oend.am+%e8 Program 2: Method Example 1 [ME1. for it too is simi%ar to Per%AP P8 ni 9name = .50-) Output: .( 6 y/” end add:p(.rb] Ruby has a 4ery f%e."e sum is+ #.here is that of method."e sum is+ <= [E"P1. )eyword. That too is +ermissib%e just %i)e it is in Per%' but e.ce+t the sim+%est case' it is not ad4isab%e to do so. It is a%so notice that &8%i)e esca+e characters can a%so be used with Ruby +rint method and the 4ariab%e re+%acement can be done with the TU V o+erator. And the +arenthesis of the method say#oodnight was dro++ed in the %ast %ie of the code.ib%e array and hashing faci%ity. )eyword.+ressions8 Program 3: Expressio E!aluatio de) add:p((5y) 8rint “. 5e define a method starting with the method name and +arameter %ists +receded by the Odef.t need to dec%are a 4ariab%e nor its ty+e when we are +%aying with it' methods return ty+es aren. The array instantiation has se4era% form' the most im+ortant one used %i)e in Python8 my$rr = >05<5”%a)inar”5-.?@ ashing is what we ca%% the associated array in Per% %ingo.A%a)inarB =C A8ulo9B5BDamiaB =C ADimiB/ 12 .rb] de) say3oodnig"t(name) result = 43oodnig"t5 4 6 name print “7nWe will miss you #.

ed but there are some added f%e. print 4&u 9y4 elsi) i == 0print 4:nlu 9y4 else print 4 #.i/ 4 end end end e(ample( ) Output: 0 < .d ha4e to use the Ogets. or &8%i)e O+rintf.am+%es from +uts in a%most a%% the codes. method' from the bui%t8in c%ass. Ruby contro% structures are $uite intuiti4e the if and whi%e statements are fo%%owed by the conditions which is o+tiona%%y Gfor the con4enience of &8 fami%y +rogrammersH 4ei%ed by the +arentheses8 Program #: $% stateme t [&trlstru&t.rb] #!/usr/bin/ruby de) e(ample( ) i = = w"ile (i E 0F) i 6= 0 i) i == .? G .ibi%ity to it which is %eft for the re%e4ant section. &u 9y 2 1 0= 00 0< :nlu 9y 0? 0F 7ina%%y' before c%osing this section' we wou%d %i)e to inc%ude the reading and writing techni$ues of Ruby. 5e ha4e a%ready used e.To access arrayAhashes' we used the s$uare brac)ets8 my$rr>=@ #output+ 0 ni 9name>A%a)inarB@ #output+8ulo9 Arrays are 6ero inde. This wi%% be a sma%%er one here' because for +rinting' we can sim+%y use the O+uts. method and to read from user in conso%e' we. ere we wou%d use gets8 Program ': (asi& $)O print) 4W"at is your nameH 4 name = gets print) 4Hello Is45name Output: W"at is your nameH EuserinputC Hello EuserinputC 1! .

This creates com+%ication and +rob%ems whi%e debugging. The Oinitia%i6e. ". 5e must use the Onew. determines the end of a b%oc)' be it c%ass' e. owe4er' we cannot ca%% the initia%i6e method direct%y' it is hidden from the non8c%ass objects. how to ma)e our Ruby code object oriented.One +rob%em with gets is that it stores the in+ut in the g%oba% 4ariab%e WX. *o the code for such a creation wi%% be8 lass Dong de) initiali!e(name5 artist5 duration) Jname = name Jartist = artist Jduration = duration end end As usua% Oend. And to ma)e our %ife easier whi%e describing those' we wou%d %i)e to ste+ into the wor%d of music and create a sam+%e a++%ication that stores songs with re%e4ant information8 A 4ery sim+%e database for song."e Calling”502F) #Corre t ?ust %i)e the to*tringG H method of ?a4a' Ruby too has a toXs method which +rints a message when an object is +assed as the +arameter to the +uts or +rtinf method.am+%e' our song database must contain a *ong c%ass because that wi%% be the abstraction for the rea% wor%d song.+ression or object. owe4er' good ruby +rogramming +ractice discourages this )ind of usage. The ne. And the re%e4ant information Gto )ee+ it sim+%e for our +ur+osesH wi%% be the name' artist and duration.2 #b$ect #riented Ruby In this section' we describe how to create c%asses' fie%ds' methods i. As the cardina% mantra of the object oriented +aradigm te%%s us' we must first create the rea% wor%d mode% of the +rob%em with the re%e4ant information showed. method described herein was the constructor. owe4er' it has to be o4er%oaded because by defau%t' the object II is +resented when toXs is ca%%ed. method for that8 myDong = Dong. 5ith this' we end u+ our 4ersion of JRuby &rash &ourseK. And a 4ersion of o4er%oaded toXis as fo%%ows8 1" .initiali!e(“Kream on”5”Lin”5?<=) #WMN#3!!! t"eDong = Dong. 7or e.t section forth wi%% treat its readers with a more detai%ed Ruby.e.new(“W"ereOer”5”.

*o' to define this c%ass we code8 lass Qarao9eDong E Dong de) initiali!e(name5 artist5 duration5 lyri s) super(name5 artist5 duration) Jlyri s = lyri s end end 1. After c%ass definition of Ruby is dissected' we are %eft with the Inheritance +art. Inheritance is the same in Ruby as it is in others' the chi%d c%ass deri4es a%% its +arent c%ass. If we start and end a c%ass at one +oint' and at another +oint we start adding other methodsAfie%ds to that c%ass and ending it again' it wi%% actua%%y aggregate them into the same c%ass.Program *: to+s a d o!erload [so g.new(4POeryt"ing454&i)e"ouse4501=) puts song0 Output: POeryt"ing+&i)e"ouse---01= (efore jum+ing to inheritance' we ha4e one more thing to discuss here.  A%% %oca% 4ariab%es start with sma%% case %etters  A%% c%ass names start with u++er case %etters  A%% fie%ds within the c%ass start with OY.  A%% c%ass methods and 4ariab%es start with OYY.s beha4iors and than)s to +o%ymor+hism' it wi%% be ta)en care of without the +rogrammer.rb] lass Dong de) initiali!e(name5 artist5 duration) Jname = name Jartist = artist Jduration = duration end de) to's( ) return 4#.s traits and inc%udes more' it may a%so o4erride its +arent. One other thing about c%ass definition is' that a c%ass definition can continue from any +oint within the code segment.Jduration/4 end end song0 = Dong.s much in4o%4ement.Jartist/---#. *u++ose we ha4ea )arao)e song as we%%' which has e4erything *ong has and more' name%y' %yrics. . There is a naming con4ention in Ruby which ma)es %ife easier than using different )eywords.Jname/+ #.

(ut what about the methodR 1n%ess' the method is o4er%oaded' the chi%d c%ass sha%% be using the +arent c%ass.Jduration/4 end end lass Qarao9eDong E Dong de) initiali!e(name5 artist5 duration5 lyri s) super(name5 artist5 duration) Jlyri s = lyri s end de) to's( ) return 4#.t(t@ Ruby on%y su++orts sing%e inheritance.Jname/+ #.Jlyri s/@4 end end song = Dong.Jartist/---#. A% we had to do is' +ut the OZ. To ma)e it use the benefits of mu%ti+%e inheritance as we%% as to a4oid the +itfa%%s thereof' The use of mi.rb@ lass Dong de) initiali!e(name5 artist5 duration) Jname = name Jartist = artist Jduration = duration end de) to's( ) return 4#. owe4er' to ma)e object more usefu% and at the same time contro%%ing the 1/ .in is in order.s methods.t(t4) puts myDong Nutput+ Dtoned+Kido---0-? Dtoned+Kido---0-?>stoned.Jname/+ #. @o other c%ass can access it. (ut if we o4erride it' then on%y the chi%d c%ass 4ersion of it sha%% be ca%%ed whene4er we ca%% it8 8rogram .+ Rn"eritan e and NOerriding >in"erit. To remember it easy we can say' *ince a +arent is a%ways o%der Gnot necessari%y bigger or moreH than chi%d' being the +arent ( is o%der than A.new(4Dtoned454Kido450-?) puts song myDong = Qarao9eDong. (ut' howe4er' A has more features Gin here' Y%yrics attributeH. owe4er' we %ea4e that ti%% the modu%e section. In Ruby' a%% fie%ds to the c%ass are +ri4ate. sign' which is o4er%oaded for inheritance o+eration. It goes %i)e this3 A Z ( means A is the chi%d of (.Jartist/---#.new(4Dtoned454Kido450-?54stoned.*o that was $uite easy.Jduration/ >#.

G Instead of this %engthy set and get attribute' Ruby ma)es our %ife easier by a%%owing us to use the attrXreader and attrXwriter. The first one wou%d be to ma)e a method that returns fie%ds and others that assigns to it8 8rogram .set gpa -.Jid/+#. with 3 after attrXreader' they become the accessor for that fie%d Gdro++ing the YH and writeab%e if attrXwriter is used.new(“%a)inar”5=00=?F=?=5-. gpa ma)inar. 5hate4er is +refi.Jname/-C#.0<) puts ma)inar.rb@ lass Dtudent Rnitiali!e(name5id5 gpa) Jname = name Jid = id J gpa = gpa de) name return Jname end de) id return Jid end de) gpa return J gpa end de) setC38$( gpa) J gpa = gpa end de) to's “#.0< %a)inar-C=00=?F=?=+-.name puts ma)inar.am+%e is gi4en be%ow Gadd it u+ to the song.J gpa/” end end ma)inar = Dtudent.rb c%ass in the endH3 12 .+ 3et and Det R >getset0. An e.access' se4era% techni$ues can be fo%%owed.G print)(“7n”) puts ma)inar Nutput+ %a)inar-.

&ontainers ma)e +rogramming more con4enient in the same way that grocery bags ma)e it easier to get our food home from the store3 They reduce the number of objects we ha4e to hand%e and the number of names we ha4e to 1M .ooh' written on it.ot.A said . 3here?A EA.irthday with love from .to'i end end aDong = Dong. puts aDong. A.8 Program .rb] Class Dong Ke) songRn%inutes= (Oalue) Jduration = Oalue/G=.ooh Today we %oo) at objects whose on%y +ur+ose in %ife is to ho%d other objects.name puts 4#.: -irtual . Milne.loc-s AIt's a Bseful . $innie the . puts aDong.new(4Si ylops45 4Lle 945 <G=) aDong.8rogram 2+ attr'reader and attr'writer >attrrw.duration/4 Si ylops <F.new(4Si ylops45 4Lle 945 <G=) aDong.sonRn%inutes = <F. 3hat's what all that writing is. ACere it is.ttribute [!irtattr." Containers+ Iterators and .ooh.duration = <F.duration Output: ? 5ith that' we c%ose our object oriented discussion for the time being and switch to &ontainers' Iterators and (%oc)s. owe4er' since e4erything in Ruby is an object anyways' the conce+t of objects wi%% a%ways be there. ". And it's got 'A Dery Cappy . And it's for putting things in. 5e can a%so add 4irtua% attributes by not rea%%y returning or setting the 4ariab%es Oas is.aDong.rb@ lass Dong attr'writer +duration attr'reader +name5+duration end aDong = Dong.

Arrays grow as needed' just as strings do. Iw(bla 9 gray green w"ite) #>4bla 945 4gray45 4green45 4w"ite4@ Arrays understand the EE and > methods' whereas ZZ means +ush and > means inserting arrays with arrays. A Ruby array can ho%d any objects. Oeggies == >4 orn45 4lettu e45 4peas4@ Oeggies>F@ = 4sTuas"4 #now Oeggies be omes #>“ orn”5lettu e5”peas”5nil5nil5sTuas"@ 7orarrays' 9%ength'range: s+ecifies subarrays3 n = >-15 -25 0<5 G5 F@ n><5-@ #UC >0<5 G5 F@ n>U<50@ #UC >G@ 5e can re+%ace subarrays in the fo%%owing fashion8 n><5<@ = >0==5 0=0@ # n == >-15 -25 0==5 0=05 F@ n>050@ = ><==5 <=05 <=<@ # n == >-15 <==5 <=05 <=<5 0==5 0=05 F@ n>?5<@ = nil # n == >-15 <==5 <=05 <=<5 F@ n><5=@ = >4two strings45 4inserted4@ # n == #>-15 <==5 4two strings45 #4inserted45 <=05 <=<5 #F@ 5hen defining an array of strings that contain no s+aces' the fo%%owing synta.remember. @ew storage s%ots are created on demand' with nils inserted when necessary.amined and changed. 5e donDt ha4e to thin) about which food items are in which bag when we are +ic)ing u+ the bags and carrying them into the house. 5ith this ana%ogy we start off with describing Ruby containers. sugar sa4es wear on our fingers and )eyboard. The w stands for words. *tring too can be considered a container but we %ea4e it to be defined in the standard ty+es8 An array is a container whose e%ements can be referred to by their +osition and whose e%ements can be e. The containers in Ruby are Arrays and ashes. A who%e +%ethora of Array o+erations are as fo%%ows3 1F .

502501@ @ *u++ose we want the item in the %ast co%umn and first row.a0 = >0=5 <=5 -=@ #UC >0=5 <=5 -=@ a< = Iw(a b) #UC >4a45 4b4@ a< EE 4 4 #UC >4a45 4b45 4 4@ a.+ressed as an array of arrays' where each EinnerE array corres+onds to a row3 # . If we remember that the inner arrays are rows' then you )now that m90: is the first row' and so Gm90:H92: is what we want3 m>=@><@ #UC 0- A detai%ed treatment of Array can be found in the %ibrary reference in the Ruby 0anua% 9PRA#0ATI&:. It. 02 01 m = > >0050<50-@5 >0?50F50G@5 >0.inde( (<=) #UC ? a-.s methods are more or %ess as same as those of Array but the difference %ies within the inde.= a< 6 a0 #UC >4a45 4b45 4 45 0=5 <=5 -=@ a-.in ludeH (4b4) #UC true a0.in ludeH (4b4) #UC )alse a-."e matri( we want+ # 00 0< 0# 0? 0F 0G # 0. can be e. ashes are another container bui%t in the Ruby %anguage. " = Has".new ">4$labama4@ = 4"umid4 ">4$las9a4@ = 4)rigid4 ">4Colorado4@ = 4ro 9y4 ">4Wis onsin4@ = 4 "eesy4 # R) you pre)er5 t"e aboOe an also be written t"is way+ 20 . which is' for ash' any object. apitali!e # error Arrays within arrays of two dimensiona% arrays can be created the same way as one dimensiona% arrays' on%y containing arrays as e%ements8 po 9et = >4wallet45 >4"ouse 9ey45 4garage 9ey4@5 4wat "4@ 7or instance' a s$uare matri.

ere is a tri4ia% e. In Ruby' the difference is main%y a different )ind of synta. A Ruby iterator is sim+%y a method that can in4o)e a b%oc).# " = . This is a common sty%e' ca%%ed higher order function sty%e' among %anguages that can hand%e functions as first c%ass objects.+%icit%y that a function can acce+t another function as an argument.its' contro% +ic)s bac) u+ immediate%y after the yie%d.rb] 21 .ist' we get ni% bac). @ow we discuss an interesting%y new conce+t in Ruby which is not direct%y found in the more )nown OOP %anguages %i)e ?a4a or &>>.am+%e' a function cou%d +erform iteration by +assing one item at a time to the name%ess function.t in which the b%oc) a++ears Gthe %oca% 4ariab%es' the current object' and so onH' and then enters the method. In other %anguages' we ha4e to s+ecify e. 1nfortunate%y' in this case %oo)s are decei4ing8 a Ruby b%oc) is a way of grou+ing statements' but not in the con4entiona% way. At first sight' a b%oc) in Ruby %oo)s just %i)e a b%oc) in &' ?a4a' or Per%. Python does it . for higher order functions. 7or e. If we %oo) u+ a )ey that doesnDt e. Inside the method' you can ca%% the b%oc) using the Oyie%d. Instead' Ruby remembers the conte.s the conce+t of b%oc)s and Iterators.ecuted' it in4o)es the code in the b%oc). This is where the magic starts. Lis+ does it. 0any other %anguages do this sty%e of +rogramming.si!e #UC ? ">4$las9a4@ #UC 4)rigid4 ">4%issouri4@ #UC nil 5hat a hash gi4es us is essentia%%y a two8co%umn tab%e with )eys in one co%umn and 4a%ues in the other. #i4e the hash a )ey' and it te%%s us the associated 4a%ue.4$labama4=C4"umid45 4$las9a4=C4)rigid45 # 4Colorado4=C4ro 9y45 4Wis onsin4=C4 "eesy4/ ". 5hen the b%oc) e.-4en & does it with function +ointers. (ut in Ruby' any method can be ca%%ed with a b%oc) as an im+%icit argument.am+%e8 Program 1/: (lo&0 a d $terator 1 [bl&0tr!. *econd' the code in the b%oc) is not e. 5ithin the method' the b%oc) may be in4o)ed' a%most as if it were a method itse%f' using the yie%d statement. (asica%%y' we can +ass a name%ess function to another function' and then that function can in4o)e the +assed8in name%ess function. )eyword with a 4a%ue. 5hene4er a yie%d is e.ecuted at the time it is encountered. (%oc)s are basica%%y name%ess functions' reminiscent of the Lambda form in LI*P or Python. It. 7irst' a b%oc) may a++ear on%y in the source adjacent to a method ca%%< the b%oc) is written starting on the same %ine as the methodDs %ast +arameter.

am+%e' we cou%d write a sim+%e function that returns members of the 7ibonacci series u+ to a certain 4a%ue8 Program 11: 1ibo a&&i [%ib.o(ma() i05 i< = 05 0 # parallel assignment w"ile i0 E= ma( yield i0 i05 i< = i<5 i06i< end end )ib:p.de) t"ree.F 2 0. 5hat ma)es b%oc)s interesting' howe4er' is that we can +ass +arameters to them and recei4e 4a%ues bac) from them. A%though it is common to +ass just one 4a%ue to a b%oc)' this is not a re$uirement< a b%oc) may ha4e any number of arguments. -ach time' it in4o)es the code in the b%oc)' and a cheery greeting is +rinted.<0 -? FF 21 In this e. This 4a%ue is +assed to the associated b%oc). In this instance' the 4ariab%e f recei4es the 4a%ue +assed to the yie%d' so the b%oc) +rints successi4e members of the series. 7or e. 5ithin this method' yie%d is ca%%ed three times in a row.am+%e' the yie%d statement has a +arameter. The most basic usage of b%oc)s is to %et us define your own way for iterating o4er the items. (ut what if you want to iterate bac)wards from the end to the beginningR In &' we ha4e to set 22 .imes yield yield yield end t"ree. (asica%%y' b%oc)s are designed for %oo+ abstraction. 7or e. In the definition of the b%oc)' the argument %ist a++ears between 4ertica% bars. V)V print )5 4 4 / Output: 0 0 < . puts 4Hello4 / Output: Hello Hello Hello The b%oc) Gthe code between the bracesH is associated with the ca%% to the method threeTimes.rb] de) )ib:p.o(0==) .imes .am+%e' if we ha4e a %ist' se$uence' 4ector' or array' you can iterate forward by using the method +ro4ided by the standard %ibrary.

0=GFG Signum . This is not good' because it re4ea%s interna% detai%s of the %ist..am+%e' des+ite being an easy %anguage' the conce+t of %ambda and the object +atterns itse%f was a hard nut to crac) for us when we were %earning Python' LI*P iteration ga4e us much a +ain' &8function +ointer is something a & newbie has to stri4e to %earn' de%egates for &8*har+. Program 12: umber. The basic ty+es that are under use in Ruby are8 /u bers Ruby su++orts integers and f%oating +oint numbers.1<<20G<F0?<G?--. *o for e. Integers can be any %ength Gu+ to a ma.imum determined by the amount of free memory on your systemH. Integers outside this range are stored in objects of c%ass Signum Gcurrent%y im+%emented as a 4ariab%e8%ength set of short integersH.-F-2GG2=. ". (y using b%oc)s' we can hide the %oo+ %ogic inside the method or function.+erience in Ruby' we can say that for Ruby' Iterators and b%oc)s were the com+%ications for us.tandard Ty&es 5hat may be the first to+ic of discussion in any other +rogramming %anguage +a+er' we de%ayed it ti%% now.G.s us hide that %ogic..rb num = 2 .type5 4 45 num5 47n4 num W= num end Li(num 2 Li(num G? Li(num ?=1G Li(num 0G.<0G Signum <20?.21?<-<=.GGG?0G0=<-FF????G?=-?F0<21G 2! .F1-F?-1F=--G Signum G<... 7or e.times do print num. Ruby %et. This +rocess is trans+arent' and Ruby automatica%%y manages the con4ersion bac) and forth.am+%e by ca%%ing %ist.' . Ruby is an unty+ed %anguage' whate4er is ca%%ed standard ty+es here are actua%%y c%asses wra++ed u+. And from out one month o%d e.' a start 4a%ue' an end com+arison' and an increment. Integers within a certain range Gnorma%%y 82!0 to 2!081 or 82/2 to 2/281H are he%d interna%%y in binary form' and are objects of c%ass Li(num. -4ery %anguage has a catch' the one that ma)es it harder for the newbies.0=0.u+ four things3 an inde. Ies+ite the conce+t is c%ear' but the syntactic ru%es is not as c%ean as other features of Ruby.re4erseXeach ' we can do a re4erse iteration o4er the %ist without )nowing how the %ist is im+%emented on the inside.?1.G-2-F.

5ithin sing%e8$uoted strings' two consecuti4e bac)s%ashes are re+%aced by a sing%e bac)s%ash' and a bac)s%ash fo%%owed by a sing%e $uote becomes a sing%e $uote.21'0<-'-?F'. 0<-?FG 0<-'?FG -F?0<-'?FG'. (ecause binary data is otherwise difficu%t to re+resent within +rogram source' we can +%ace 4arious esca+e se$uences in a string %itera%. ViV print i5 4 4 / 11. Others inc%ude u+to and downto' for iterating u+ and down between two integers' and ste+' which is more %i)e a traditiona% for %oo+.21 =(aabb =-. The ty+e of string de%imiter determines the degree of substitution +erformed. *trings are often created using string %itera%s3 se$uences of characters between de%imiters.times .e! tries to in4o)e the method e! in c%ass 7i.rb] -.5e write integers using an o+tiona% %eading sign' an o+tiona% base indicator G= for octa%' =( for he. Bou must fo%%ow the decima% +oint with a digit' as 1. 1G 1F F= FF G= GF ..upto(F) .F 2= .' or =b for binaryH' fo%%owed by a string of digits in the a++ro+riate base. 5hereas in the doub%e $uote a%% the esca+e character 2" . Integers a%so su++ort se4era% usefu% iterators. *o' un%i)e &> >' we find the abso%ute 4a%ue of a number by writing a@umber. -ach is re+%aced with the corres+onding binary 4a%ue as the +rogram is com+i%ed.? F 11 12 1.num.abs' not absGa@umberH. 5eD4e seen one a%ready8 . -=b0=0'=0= # # # # # # # Li(num Li(num (unders ore ignored) #egatiOe Li(num Signum He(ade imal N tal Sinary (negated) A numeric %itera% with a decima% +oint andAor an e.step(2=5 F) . Program 13: $ teger 2oopi g 3e&h i4ues [iloop. *trings are objects of c%ass Dtring. 1nderscore characters are ignored in the digit string. print 4X 4 / 0.tring: Ruby strings are sim+%y se$uences of M8bit bytes. They norma%%y ho%d +rintab%e characters' but that is not a re$uirement< a string can a%so ho%d binary data.times. A%% numbers are objects' and res+ond to a 4ariety of messages.= .. ViV print i5 4 4 / F=.downto(1F) .+onent is turned into a 7%oat object' corres+onding to the nati4e architectureDs doub%e data ty+e. ViV print i5 4 4 / Output: X X X 0 < .

MR#3 A here document consists of %ines in the source u+ to' but not inc%uding' the terminating string that you s+ecify after the EE characters. [\Q e%%o ThereQ is e$ua4a%ent to J e%%o ThereK 7ina%%y ere Iocuments can a%so be used to construct *trings3 aDtring = EEP#K'NL'D. J-at at TUauthorV=sK Then the first one wi%% +rint -at at TUauthorV=. [$A e%%o ThereA is e$ua4a%ent to O e%%o There. In good com+uter science tradition' RubyDs indices are counted starting with 6ero instead of one.DD [$ and [\ start de%imited sing%e8 and doub%e8$uoted strings. Putting this +air of numbers in s$uare brac)ets' we can e. . 5or)ing with Array and *trings is $uite simi%ar. There are three more ways to construct string %itera%s3 IT' IY' and CChere documents. 7or e. @OT-3 In this section' since the codes are e.am+%e' if' in irb' we ty+e3 O-at at TUauthorV=. 2. -ach +osition in a string has a numerica% inde. In fact it was mentioned when we were mentioning containers that *tring too is a container in Ruby but it wi%% be discussed under data ty+es because that is more in the sense of an a4erage +rogrammer or 6ea%. @orma%%y' this terminator must start in the first co%umn.treme%y tri4ia%' we wou%d be using the IR( interacti4e inter+reter for Ruby.MR#3 .."e body o) t"e string is t"e input lines up to one ending wit" t"e same te(t t"at )ollowed t"e ZEEZ P#K'NL'D.s whereas the second one wi%% yie%d' -at at 0afinar.re+%acements as we%% as the 4ariab%e re+%acements are done.s. owe4er' if you +ut a minus sign after the EE characters' you can indent the terminator. As an e. *egments of a string' or substrings' are referred to by their starting +ositions and %engths. The method is sim+%e' just after ty+ing IR( Gsma%% ca+s in 1@ILH we can get the immediate resu%ts after ty+ing in the commands.s' +ro4ided that author 4ariab%e has the 4a%ue 0afinar.amine or modify indi4idua% characters or %onger substrings.am+%e' if' in irb' we ty+e +rintf J e%%o 5or%dK then in the immediate %ine.

up ase 6 bar>U050@ #UC bar>U. )oo>05F@ = 4i4 # )oo == 4wine4 )oo>05<@ = 4edg4 # )oo == 4wedge4 ItDs sometimes more con4enient to count from the end of the string than from the beginning. The %ast character is considered to be in +osition 81' the ne. enter(.5?@ #UC bar>U. This means that using s$uare brac)ets to feed +osition information to a string is just another way of a++%ying a method to an object< the notation may be new' but the conce+t is no different from what we were ta%)ing about on Iay 2.reOerse # bar == 4WPK3Pegdew4 4w4 43Peg4 # bar == 4WPKdew4 If we ta)e a %oo) at bar. bar = )oo. The affected string e.r[ust(.t8 to8%ast in +osition 82' and so on. 4ab 4.5?@ = 44 )oo.)oo = 4wis"bone4 )oo>=50@ #UC 4w4 )oo><5F@ #UC 4s"bon4 )oo>=50@ = 4)4 # )oo == 4)is"bone4 )oo>F50@ = 4a4 # )oo == 4)is"bane4 )oo>=5?@ = 4wol)4 # )oo == 4wol)bane4 A re+%acement string does not need to be the same %ength as the segment it is re+%acing. E9:E cou%d ha4e been ca%%ed EsubstringE or Es%iceE' and E9:NE cou%d ha4e been ca%%ed Ere+%aceXsubstring.) #UC 4 ab 4 4ab 4. enter(G) #UC 4 ab 4 (odd spa es go to t"e rig"t) 4ab 4.) #UC 4ab 4 4ab 4.methods and scan through the %ong %ist it gi4es you' weD%% see E9:E and E9:NE in there.E A++end either another string or a character3 ( ( ( ( = 4one 4 EE ?1 #UC 4one 04 (?1 is $DCRR )or 404) EE 4 two 4 #UC 4one 0 two 4 EE H< #UC 4one 0 two <4 (same as ( EE F=) l$ust0length1+ center0length1+ r$ust0length1 Pad with %eading and trai%ing s+aces as necessary to grow to the gi4en %ength.l[ust(.+ands or contracts as needed.) #UC 4 ab 4 4ab 4. enter(<) #UC 4ab 4 (no "ange i) lengt" is too small) count0descri&tion1 2/ .

s = 4ab de ab de4 s.delete(4a Ue4) #UC 4b b4 downcase+ u&case+ swa&case+ ca&itali2e Return a co+y with ca+ita%i6ation changed. apitali!e #UC 4$b 4 include30s&ec1 Return true or )alse de+ending on whether the string contains s+ec' which can be a string or a character. Again' s+ec can be either a string or a character. 4aS 4aS 4aS 4aS 4. 4Haysta 94. 4%ississippi4.inde((4ssi4) #UC < 4%ississippi4.inde((4sp4) #UC nil (not )ound) rinde40s&ec+ 5li it61 Li)e inde(' but find the %ast match instead of the first. ount(4 4) #UC < s.in ludeH(4needle4) #UC )alse 4Haysta 94.<) #UC true (be ause HH is . 4%ississippi4.up ase #UC 4$SC4 4.Return the number of characters that match those in the descri+tion string.rinde((4i4) #UC 0= 4%ississippi4.in ludeH(. s = 4ab de ab de4 s. ount(4bUe4) #UC 2 delete0descri&tion1 Li)e ount' but return a co+y with a%% matching characters remo4ed. The %imit sto+s the search.inde((4ssi45-) #UC F 4%ississippi4.4.down ase #UC 4ab 4 4.in ludeH(4sta4) #UC true 4Haysta 94.swap ase #UC 4$bC4 4.<) inde40s&ec+ 5offset61 7ind the inde. where s+ec is found' starting either from the beginning or from offset. A range of characters can be s+ecified with a dash' as in 4a.rinde((4i45G) #UC ? stri& 22 .

The first e. The two8dot form creates an inc%usi4e range' whi%e the three8dot form creates a range that e.am+%e here simu%ates the down ase method.. That is because *trings are not on%y a usefu% +art in Ruby +rogramming' but a%so in +rogramming in genera%.e(t4 4%on9ey4.ZbatZ).5 25 1@ (ZbarZ.4.to'a #05 <5 -5 ?5 F5 G5 .PX.c%udes the s+ecified high 4a%ue.strip #UC 4Prie Canal4 tr0s&ec+ re&l1 *hort for Etrans%ate. 4Prie Canal 7n4.1). 7or e.. *e$uences ha4e a start +oint' an end +oint' and a way to +roduce successi4e 4a%ues in the se$uence..E Return a co+y with characters from s+ec re+%aced by the corres+onding characters from re+%. If Ruby is to he%+ us mode% rea%ity' it seems natura% for it to su++ort these ranges.hausti4e +art of the section.0 through /2' and so on. *ome interesting +oints regarding Ranges are as fo%%ows3 • The first and +erha+s most natura% use of ranges is to e. 4KND'LR&P.to'a #>4bar45 4bas45 4bat4@ • As we%% as re+resenting se$uences' ranges may a%so be used as conditiona% e.+ressions.am+%e' the fo%%owing code fragment +rints sets of %ines from standard in+ut' where the first %ine in each set contains the word CCstartDD and the %ast %ine the word JendK.K and J]K range o+erators. Ranges Ranges occur e4erywhere3 ?anuary to Iecember' 0 to F' rare to we%%8done' %ines .tr(4ymUT454NW+])H4) #UC 4%]+9eN4 This has been a rather e. In Ruby' these se$uences are created using the J.+ress a se$uence.. In fact' Ruby goes one better3 it actua%%y uses ranges to im+%ement three se+arate features3 se$uences' conditions' and inter4a%s. (0. w"ile gets print i) /start/.tr(4$U\454aU!4) #UC 4dos')ile.Remo4e whites+ace Gin4isib%e characters such as s+aces' tabs' %inefeeds' and so forthH from the beginning and end./end/ end 2M .

]7sW>a-!@/ #/]7sW>a-!@/ #/]7sW>a-!@/ #/]7sW>a-!@/ Once you ha4e a regu%ar e.. They can be created by ca%%ing the constructor e.0?0F1 #true Z Z #true Z!Z #)alse Regular 74&ression: One thing that made Per% as usefu% as it is des+ite its ug%iness is the usage $uic)ness of the Regu%ar -.+ression object' you can match it against a string using Mege(p#mat "(aString) or the match o+erators =^ G+ositi4e matchH and !^ Gnegati4e matchH.+.Z[Z) (ZaZ.+ression. If both o+erands of the match o+erator are Dtrings' the one on the right wi%% be con4erted to a regu%ar e. The match o+erators are defined for both Dtring and Mege(p objects.0=) (0.+%icit%y or by using the %itera% forms ApatternA and [r=pattern=.+ressions are used to match +atterns against strings. Regu%ar e. Regu%ar e. a = Mege(p.Z[Z) === === === === === F #true 0F #)alse -. 5e can use this to write a method' showR-' which i%%ustrates where a +articu%ar +attern matches.+ressions are objects of ty+e Rege..0=) (ZaZ..new(Z]7sW>a-!@Z) b = /]7sW>a-!@/ = Ir. W^ recei4es the +art of the string that was matched by the +attern' WC recei4es the +art of the string that +receded the match' and WD recei4es the string after the match. (0. The match o+erators return the character +osition at which the match occurred. a a a a = 4Lats =^ /a/ =^ /!/ =^ 4ll4 Waller4 # 0 # nil # .• A fina% use of the 4ersati%e range is as an inter4a% test3 seeing if some 4a%ue fa%%s within the inter4a% re+resented by the range..0=) (0. Program 1#: 5E [re.. Ruby +ro4ides bui%t8in su++ort that ma)es +attern matching and substitution con4enient and concise' simi%ar to that of Per%' on%y organi6ed.rb] de) s"owMP(a5re) 2F . They a%so ha4e the side effect of setting a who%e %oad of Ruby 4ariab%es.+ressions. This is done using ===' the case e$ua%ity o+erator.

8 74&ressions A%though some e.+ressions is a to+ic huge enough to deser4e its own +a+er and hence any further discussions..am+%e' the i) and ase statements both return the 4a%ue of the %ast e.new(01-F5 05 0) Dong++.+ressions in Ruby.0= t"en !0 . One of the first differences with Ruby is that anything that can reasonab%y return a 4a%ue does3 just about e4erything is an e.+ression e. "._a/CC#.+ressions were co4ered in the section !.ecuted. 7or e.ype == %8-++ba!! i) song.written E Kate.+ressions. 7or e._Z/4 else 4no mat "4 end end s"owMP(ZOery interestingZ5 /t/) s"owMP(ZLats WallerZ5 /ll/) Output: Oery inEEtCCeresting Lats WaEEllCCer The ru%es and regu%ations of Regu%ar -.mp-.+ression.+ressions' we end our discussion about the standard data ty+es of Ruby.+ressions are %isted be%ow3 • *tatements can be chained in Ruby a N bN c N dN e N .radba!! else Dong++ba!! end else Dong++Nt"er end rating = ase OotesCast w"en =.0' in this section we wi%% treat the to+ic with more em+hasis because no discussion about a %anguage wou%d be com+%ete without a +ro+er treatment of -. *ome to+ics about Ruby -. And a%ong with regu%ar e.am+%e8 song._`/EE#.i) a =^ re 4#.. • Things that are norma%%y statements in & or ?a4a are e.ype = i) song.

su end end (y incor+orating b%oc) $uotes' we can use o+erating system commands8 Program 1': Comma d Expressio s #!/usr/bin/ruby )or i in =. Ruby su++orts a%% the standard boo%ean o+erators and introduces the new o+erator definedR. They e4a%uate their second o+erand on%y if the first is fa%se. The on%y difference in the two forms is +recedence GJandK binds %ower than J^^KH. *imi%ar%y' both JorK and JaaK e4a%uate to true if either o+erand is true.ecute CC6DD' +assing as a +arameter."isNne w"en 0=. Bou then as) the object that resu%ts from that ca%cu%ation to e.act%y e$ui4a%ent to writing8 Ga._GbHH.F= t"en Mating++CouldKoSetter else Mating++MaOe end In Ruby' many o+erators are actua%%y method ca%%s.>GcH *imi%ar%y' we can a%so o4er%oad o+erators' a%% it needs is to redefine the Zo+erator method` of that c%ass3 lass Li(num alias old8lus 6 de) 6(ot"er) old8lus(ot"er). JnotK and JQKD return the o++osite of their o+erand Gfa%se if the o+erand is !1 . ?ust to ma)e %ife interesting' CCandDD and CCorDD ha4e the same +recedence' whi%e CC^^DD has a higher +recedence than JaaK.`ls Ual` end Output: Calls t"e ls Ual t"ree times in a :#RX enOironment • • Ruby has a sim+%e definition of truth.... 5hen you write aWb6 youDre actua%%y as)ing the object referenced by a to e.• • Mating++D9ip.ecute the method CCWDD' +assing in the +arameter b. Any 4a%ue that is not ni% or the constant fa%se is true. They e4a%uate the second o+erand on%y if the first is true Gthis is sometimes )nown as Jshort8circuit e4a%uationKH. (oth JandK and J^^K e4a%uate to true on%y if both o+erands are true. As with JandK' the on%y difference between CCorDD and CCaaDD is their +recedence. This is e.

And' yes' JnotK and JQK differ on%y in +recedence. ?ust %i)e &A?a4a' Obrea). is a4ai%ab%e in Ruby as we%% in the form of Obrea)..+ressions are e$ua4a%ent8 i) rain == “true” puts “donBt go out!” puts “donBt go out” i) rain == “true” • • • The %oo+ing techni$ues of Ruby ha4e been introduced +re4ious%y as with the Iterators.rig 8R = -. Anything contained within the Cdef modu%e ..t. de)ineH 0 #dumy de)inedH “%a)inar” # onstant de)ined -. and Ogoto.sin(() # . 7or %oo+ ta)es a range and Iterates through it.rig. If the argument is yie%d' definedR returns the string Dyie%dD if a code b%oc) is associated with the current conte.t. 5hen we write bigger codes the +robabi%ity of name c%ash increases. re+eats the current %oo+.rig. and Ogoto. restarts the %oo+' whi%e Oredo.continue. ". end de) . In here we wou%d introduce the If o+erator which is much %i)e the same in Per%' the fo%%owing to e.0?0F1<GF? de) . (ui%t ins %i)e whi%e and for %oo+s don.. At times %i)e those' the conce+t of 0odu%es come to our rescue. module ..t introduce any new sco+e. It additiona%%y introduces tow new )eywords Oredo. The definedR o+erator returns ni% if its argument is not defined' otherwise it returns a descri+tion of that argument. . enca+su%ates a modu%e.'. shows the 7or %oo+.• true' and true if the o+erand is fa%seH.abs # met"od 5e ha4e a%ready gone through the conditiona% statement I7 ni a +re4ious section. and Oretry.ne.sin(.9 %odules 0odu%e is to Ruby is what names+ace is to &>>A&T.'. Oretry. os(() # . owe4er one was missed.rig++8R/?) !2 . Program 1. end.rig. 5hich is the 7or statement. . end end Any +rogram using this modu%e wi%% be %i)e8 reTuire 4trig4 y = .

. Ruby can create better manageab%e &#I than Per% !! .ra 9.type. • 5eb Programming3 0OIXR1(B is a4ai%ab%e for A+ache.. 5hen this ha++ens' a%% the modu%eDs instance methods are sudden%y a4ai%ab%e as methods in the c%ass as we%%.to's/4 end end lass 8"onograp" in lude Kebug # . end p" = 8"onograp". And with the +ower of embedding regu%ar e.sel)..=)+ West Pnd Slues4 4Pig"t.name/ (7##.new(4West Pnd Slues4) et = Pig"t.0i. This is because it is a re%ati4e%y new %anguage and initia%%y most of its documentations were in ?a+anese. @ot yet. owe4er' we can include a modu%e within a c%ass definition..0 :sing Ruby Ruby is not a wide%y used %anguage a%% o4er the wor%d. In modu%es' we usua%%y define modu%e methods' methods whose names are +refi.+ressions as we%% as the command e.ed8in modu%es effecti4e%y beha4e as su+erc%asses. This is simi%ar to c%ass methods' @ow the thought goes3 CCwhat ha++ens if I define instance methods within a modu%eRDD There comes mi.in is a wonderfu% by8+roduct of the 0odu%e conce+t. Program 1*: Mixi s [mixi .sel).GG0.sel).new(4Durrealisti 8illow4) p".w"o$mRH Output: 48"onograp" (#F-.+ression faci%ity' Ruby is essentia% for Process management. A modu%e canDt ha4e instances' because a modu%e isnDt a c%ass.w"o$mRH et. In fact' mi.id/)+ #...ra 9 in lude Kebug # .rb] module Kebug de) w"o$mRH 4#.ed by the modu%e name.ra 9 (#F-.GF2G=)+ Durrealisti 8illow4 (y inc%uding the Iebug modu%e' both Phonogra+h and -ightTrac) gain access to the whoAmIR instance method. '. owe4er' as times +asses and no trace of Per% / has been shown' Ruby has a good chance to ta)e its +%ace as Per% is 4ery notorious for being nasty in %oo)s. end lass Pig"t.in. Ruby has fo%%owing usage8 • Process 0anagement3 ?ust %i)e Per%' Ruby can be g%ued to the o+erating system. Anything can be done with Per% can be done with Ruby. They get mi:ed in.

GProgramming Language Princi+%eH is the course for which this +a+er has been +re+ared for. Ruby is as object oriented as *ma%%ta%)' and inf%uenced by the synta.C "28 &*& !2. 5ith an e.t mani+u%ation. Lambda by LI*P and Python' Iterator by Ruby' Patterns by *ma%%ta%) are on%y a few to mention. • !" . The reason *ma%%ta%) or -iffe% cou%d be usefu% is the same reason Ruby can be taught. Iifferent %anguages ha4e different features embedded in them.t section discusses about the use of Ruby as a case +rogramming %anguage in &*& !2. Ruby can a%so be used as a modu%ar +rogramming tongue since it can a%so embed and im+ort modu%es to and from the en4ironment.ce+tion of %earning the tough issues %i)e Iterators and (%oc)s' we hard%y fe%t a hurd%e in %earning a %anguage that was com+%ete%y new and obscure and we enjoyed e4ery moment of it. Ies+ite being object oriented it is different from ?a4a' des+ite being scri+ting %anguage it is better %oo)ing than Per%' and des+ite being both of these' it is easier than Python.+ected of a +erson +assing this course to be ab%e in +rogramming %anguage we%% enough to gras+ a %anguage with just %oo)ing at the s+ecification or manua%.Our ho+e is that this %anguage wi%% be +o+u%ar among the networ) administrators and +rogrammers' and aid them in bui%ding their +rogramming ca%isthenics whi%e sa4ing a %ot of time and brain cyc%es. 9. 5e +ic)ed Ruby because we wanted a change. A%so the Array hand%ing ca+abi%ity of Ruby is e.0 Ruby as a Case *anguage for C. Ruby' a%though object oriented in +aradigm' and scri+ting %anguage in nature' +ro4ides us with an en4ironment we ne4er seen before. 8. of -iffe%.List Processing3 Ruby has some LI*P %i)e features %i)e %ambda Gin the form of iterators and b%oc)sH. In some AI +rogramming Ruby can be used • Ruby can a%so be used for a case study in Programming Language &ourses because it contains some of the more ad4anced features few other %anguages +ro4ide. Our ne.. 7or a case %anguage in &*& !2. Instead of Per%' Ruby can be taught to +ro4ide us with the f%e. It is' to our minds' im+erati4e to inc%ude those features in a %anguage course %i)e !2.0 Conclusion In this +a+er' our objecti4e was to demonstrate our abi%ity of %earning a new %anguage' and ana%y6ing it from whatsoe4er we ha4e %earnt.' as it wou%d bui%d u+ the 4ocabu%ary of a student. And ha4ing those terms in mind' no other %anguage wou%d +ro4ide us with the o++ortunities of im+ro4ing that 4ocabu%ary than Ruby. In (ang%adesh' few +rogrammers e4en )now the name Ruby as a +rogramming %anguage.ibi%ity or te. And since this course dea%s with the different +rogramming %anguage' it is a%so e. Instead of Python' Ruby can be tought to introduce us to a mu%ti8+ur+ose c%ean %anguage. or simi%ar +rogramming %anguage course' Ruby can be the best se%ection.treme%y +owerfu%.

.. <esign Patterns 5included with the C<6 526 Instant :%*+ Wro4 Publishers 5"6 <a=e Tho as and Andy !unt.Progra ing Ruby+ the Prag atic Progra er>s (uide 5'6 Ruby ?A@.orgAfa)A !.ibliogra&hy 516 (a a. A=ailable online in: htt&:AAwww..rubygarden.0 A&&endi4 I: .