Sunteți pe pagina 1din 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

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. <,=

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. 5hen he became more e.+erienced' he %i4ed his dream and de4e%o+ed Ruby. It is forecasted by some enthusiast Gto others they are o4er86ea%ousH that Ruby is enough to re+%ace Per%. 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. 0oreo4er' 0at6 +referred writing codes to writing documentation' which near%y doomed the %anguage;s s+read beyond far8east. 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. The beautifu% %anguage as Ruby is' it didn;t ta)e time for it to go in the same trac) as the big guns %i)e Python and Per%. 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. 7or that' Bu)ihiro 0atsumoto is than)s the Ruby community8 3hey &ecame interested in a lesser known language from the 'ar >ast. 3hey researched it, read thousands of lines of source code, wrote uncounta&le test scripts and e mails, clarified the am&iguous &ehavior of the language, found &ugs /and even fi:ed some of them1, and finally compiled this great &ook. %u&y is certainly well documented now? <,= (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. 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;s birthstone. Ruby is de4e%o+ed under Linu.' and is written in fair%y straightforward &. It runs under 1@IL' IO*' 5indows F,AFMA@TA2000' 0ac O* L' (eO*' Amiga' Acorn Risc O*' and O*A2. The current 4ersion of Ruby is 1.M.2' the first 4ersion was 0.F, 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.ce+t a few web8centric ones where we used Linu. *1*- F.1. 2." #b$ect Pri er One of the factors that moti4ated Ruby;s creator to attem+t a new %anguage in the first +%ace was +erfect object orientation. If c%ean%iness was the on%y factor' Python was a%ready a4ai%ab%e. Bu)ihiro 0atsumoto had dreamed a

"

+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. 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. 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. In this section' no %anguage s+ecific issues or syntactic sugars sha%% be raised' those are sa4ed for %ater use. The first thing in order is a definition of an object. To +ut it sim+%y' an object is an atomic entity' formed from the union of state and beha4ior. It +ro4ides an enca+su%ation re%ationshi+ that ensures a strong interna% cohesion' and a wea) cou+%ing with the outside. An object re4ea%s its true ro%e and res+onsibi%ity when' by sending messages' it becomes +art of a communication scenario 92:. In a more %ay term' an object is sim+%y as it;s described in the %e.icon' informa%%y we may ca%% it sim+%y' a thing. *omething that e.ists' something that has some attributes' something that can show some beha4ior. Programming has a%ways been re+resentation of a so%ution to a +rob%em in an a%gorithmic a++roach. 7unctions +%ay the ro%e of sub8jobs which acts as bui%ding b%oc)s towards the so%ution. owe4er' from a +rogrammer;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. 7or e.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.e. instructors' students' courses etc. a%ong with the same set Gor the necessary set' one can;t e.+ect the co%or of the students eyes to be in+uttab%e for the +rogram' it;s not necessary' and is ca%%ed abstractionH' then the +rob%em is ha%f so%4ed in the +enci% and +a+er. That;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. That goes the %ay man;s a++roach in the +aradigm. There is much more to object orientated +aradigm to that. 5ho%e courses and +%ethora of boo)s ha4e been de4oted to treat that to+ic. In this section' on%y the re%e4ant of it sha%% be touched and the other to+ics sha%% be gradua%%y e.+%ained in the necessary sections. According to some e.+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. The fi4e conce+ts are gi4en be%ow8

#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. 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. 5e must be ab%e to send defined messages to them and recei4e feedbac) from them. They must ha4e their +ri4acy and +ub%icity. In a more forma% way to s+ea)' we can say that an object com+rises of states and beha4iors. 0athematica%%y8 Object N *tate > (eha4ior The state of an object means the attributes that object has' for e.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; object. It may show beha4iors %i)e' acce%erate' bra)e and tight turn. (eha4iors are ca%%ed methods in many %anguage terms. (y the way' the e.am+%e of 0a6da 0iyata is ins+ired by the game we recent%y +%ayed' @7* 1nderground 21.

Any reference on @7* 1nderground 2 is made by 0afinar Rashid Phan. It is one of my current obsessions 888 0afinar R Phan

%essage Let;s now thin) of the 4irtua% wor%d of @7* 1nderground 2. On o+ening the game' we ha4e a city where different cars roam about' the +%ayer;s car is to find the different s+ot and start off with a race. A car may ha4e the attributes mode%s' to+ s+eed etc. as we%% as the beha4iors name%y turn %eft' turn right' co%%ide etc. (ut to +erfect%y interact in an interacti4e scenario' one object must send a message to another object. Or' the beha4ior shou%d be in4o)ed to that object. And that is what;s ca%%ed message. *u++ose' the +%ayer +resses the 1+ direction )ey of hisAher )eyboard that shou%d mean the +%ayer;s car shou%d acce%erate' and it shou%d mo4e forward. @ow' what ha++ens to the +%ayer in the object wor%d is' the message Omo4e; is +assed to the car which ignites the beha4ior of mo4ement in it. 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. Our e.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.+%anation of the messages wou%d be %eft for the more Ruby re%e4ant sections. Class *o far we ha4e on%y described objects' entities with beha4iors and attributes' and our e.am+%es were 0iyata and -c%i+se. (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. *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. The conce+t of c%ass is to sa4e us from that di%emma. &%asses act %i)e a tem+%ate. 7or e.am+%e' the abstract car has the attribute' co%ors' mode% and to+ s+eed. It shows the beha4iors bra)e' dece%erate and acce%erate. *o when we say &ar A is a car object' then it must ha4e a%% those attributes fi%%ed and beha4iors shown. &%ass is the coo)ie cutter where the objects are the coo)ies. 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. And a c%ass may a%so ha4e its own ty+e as an attribute. *uch as a Person c%ass may ha4e another Person c%ass in the form of s+ouse. &%asses are what ma)es the word abstraction associated with the object oriented conce+t. Inheritance 5e ha4e discussed c%asses' messages and objects' and inheritance is a sweet Gand con4enientH addition to the object oriented +aradigm. It is an interre%ationshi+ among c%asses which sums u+ to something %i)e this8

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

readab%e' writeab%e or readAwritab%e 4ia +ro+erties or accessor methods. It is customary to ha4e a%% the attributes of a c%ass +ri4ate and %et the accessors +%ay the )ey ro%e in readingAwriting. Another im+ortant theme in Object conce+t is Iesign Pattern. 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. The conce+t is immorta%i6ed by +ure object oriented %anguages %i)e *0ALLTALP' (-TA' -iffe% and Ruby. ?a4a a%so has the abi%ity of ada+ting design +atterns though its not mandatory. The who%e *wing %ibrary in ?a4a embraces the 0S& G0ode% Siew &ontro%%erH architecture which is a core of design +atterns. In Ruby' Patterns +%ay a 4ery im+ortant ro%e and a who%e section is dedicated to the conce+t. 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. 7or e.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. *imi%ar%y' in a windows en4ironment' the button may wait fore4er to recei4e user in+ut. 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. (y the way' such a +attern is coined as the JObser4er PatternK. Thus' this introductory section on Object Oriented +aradigm ends. And as +romised' we +ut no syntactic annoyance' not yet to say the %east. In fo%%owing set of sections' more ORuby8centric; definition and im+%ementation of those conce+ts wi%% be e%aborated as necessary. 2.' (etting Ac)uainted with a Ruby Progra After rather e.hausti4e sections on definitions' history and to+ica% +rimers' this section starts off with the %anguage itse%f. This is a sma%% section in which we de+ict a bare8bone Ruby +rogram' fo%%owed by the ways to run it. 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. The ruby code for it goes %i)e this8 Code 1: Hello World [hello.rb] #!/usr/bin/ruby #begins . . . print Hello World!!! #prints Hello World!!! #done output: Hello World

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

10

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. Object instantiation is done Ruby with ca%%ing the constructor. 7or e.am+%e' %et;s su++ose we are creating a new instance of the &ar object whereas &ar is an a%ready defined c%ass. *o we wou%d code8 myCar = Car.new( )#a no-arg onstru tor yourCar = Car.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. &omments are fo%%owed by a +ound sign' OT;' reminiscent of Per%APython. In Ruby' a uni$ue object II is assigned to each object created. 5e )now the II of the object by ca%%ing the id attribute of that object' i.e. my&ar.id' your&ar.id etc. 5ithin each c%ass' we can define instance methods. -ach method is a chun) of functiona%ity which may be ca%%ed from within the c%ass and from outside. These instance methods in turn ha4e access to the objectDs instance 4ariab%es' and hence to the objectDs state. 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.trum+etG12!H -.act%y %i)e ?a4aA&>>' the dot o+erator is used as accessing o+erator of a c%ass or object. 7or instance8 Class#ame.new( onstru tor$rguments) Class#ame. lass%et"od( argument&ist) #or stati instan e#ame.instan e%et"od( argument'list ) ( = instan e#ame.)ield y = lass#ame. 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.act same manner8 %a)inar.lengt" #output+ , -.times.print wow/ #output+ wowwowwow -0120.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+%es thereof. The first issue to be discussed 11

here is that of method. ?ust %i)e we don;t need to dec%are a 4ariab%e nor its ty+e when we are +%aying with it' methods return ty+es aren;t re$uired either. 5e define a method starting with the method name and +arameter %ists +receded by the Odef; )eyword. In Ruby' e4ery b%oc) is ended with the Oend; )eyword. 7or e.am+%e8 Program 2: Method Example 1 [ME1.rb] de) say3oodnig"t(name) result = 43oodnig"t5 4 6 name print 7nWe will miss you #.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;t ha4e any im+act in the b%oc)ing or sco+e as in +ython' but it is high%y recommended. And the +arenthesis of the method say#oodnight was dro++ed in the %ast %ie of the code. 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. The TU V o+erator can a%so be used %i)e the e4a% function Gin Per%H that e4a%uates e.+ressions8 Program 3: Expressio E!aluatio de) add:p((5y) 8rint ;"e sum is+ #.( 6 y/ end add:p(,50-) Output: ;"e sum is+ <= [E"P1.rb]

Ruby has a 4ery f%e.ib%e array and hashing faci%ity. The array instantiation has se4era% form' the most im+ortant one used %i)e in Python8 my$rr = >05<5%a)inar5-.?@ ashing is what we ca%% the associated array in Per% %ingo. The synta. for it too is simi%ar to Per%AP P8 ni 9name = .A%a)inarB =C A8ulo9B5BDamiaB =C ADimiB/

12

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.ed but there are some added f%e.ibi%ity to it which is %eft for the re%e4ant section. 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 == , print 4&u 9y4 elsi) i == 0print 4:nlu 9y4 else print 4 #.i/ 4 end end end e(ample( ) Output: 0 < - ? G , &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. This wi%% be a sma%%er one here' because for +rinting' we can sim+%y use the O+uts; or &8%i)e O+rintf; method and to read from user in conso%e' we;d ha4e to use the Ogets; method' from the bui%t8in c%ass. 5e ha4e a%ready used e.am+%es from +uts in a%most a%% the codes. 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!

One +rob%em with gets is that it stores the in+ut in the g%oba% 4ariab%e WX. This creates com+%ication and +rob%ems whi%e debugging. owe4er' good ruby +rogramming +ractice discourages this )ind of usage. 5ith this' we end u+ our 4ersion of JRuby &rash &ourseK. The ne.t section forth wi%% treat its readers with a more detai%ed Ruby. ".2 #b$ect #riented Ruby In this section' we describe how to create c%asses' fie%ds' methods i.e. how to ma)e our Ruby code object oriented. 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. 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. 7or e.am+%e' our song database must contain a *ong c%ass because that wi%% be the abstraction for the rea% wor%d song. And the re%e4ant information Gto )ee+ it sim+%e for our +ur+osesH wi%% be the name' artist and duration. *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; determines the end of a b%oc)' be it c%ass' e.+ression or object. The Oinitia%i6e; method described herein was the constructor. owe4er' we cannot ca%% the initia%i6e method direct%y' it is hidden from the non8c%ass objects. 5e must use the Onew; method for that8 myDong = Dong.initiali!e(Kream on5Lin5?<=) #WMN#3!!! t"eDong = Dong.new(W"ereOer5;"e Calling502F) #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. owe4er' it has to be o4er%oaded because by defau%t' the object II is +resented when toXs is ca%%ed. And a 4ersion of o4er%oaded toXis as fo%%ows8

1"

Program *: to+s a d o!erload [so g.rb] lass Dong de) initiali!e(name5 artist5 duration) Jname = name Jartist = artist Jduration = duration end de) to's( ) return 4#.Jname/+ #.Jartist/---#.Jduration/4 end end song0 = Dong.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. There is a naming con4ention in Ruby which ma)es %ife easier than using different )eywords. 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; One other thing about c%ass definition is' that a c%ass definition can continue from any +oint within the code segment. 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. 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;s traits and inc%udes more' it may a%so o4erride its +arent;s beha4iors and than)s to +o%ymor+hism' it wi%% be ta)en care of without the +rogrammer;s much in4o%4ement. *u++ose we ha4ea )arao)e song as we%%' which has e4erything *ong has and more' name%y' %yrics. *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,

*o that was $uite easy. A% we had to do is' +ut the OZ; sign' which is o4er%oaded for inheritance o+eration. It goes %i)e this3 A Z ( means A is the chi%d of (. 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. (ut' howe4er' A has more features Gin here' Y%yrics attributeH. (ut what about the methodR 1n%ess' the method is o4er%oaded' the chi%d c%ass sha%% be using the +arent c%ass;s methods. (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.rb@ lass Dong de) initiali!e(name5 artist5 duration) Jname = name Jartist = artist Jduration = duration end de) to's( ) return 4#.Jname/+ #.Jartist/---#.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#.Jname/+ #.Jartist/---#.Jduration/ >#.Jlyri s/@4 end end song = Dong.new(4Dtoned454Kido450-?) puts song myDong = Qarao9eDong.new(4Dtoned454Kido450-?54stoned.t(t4) puts myDong Nutput+ Dtoned+Kido---0-? Dtoned+Kido---0-?>stoned.t(t@ Ruby on%y su++orts sing%e inheritance. 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.in is in order. owe4er' we %ea4e that ti%% the modu%e section. In Ruby' a%% fie%ds to the c%ass are +ri4ate. @o other c%ass can access it. owe4er' to ma)e object more usefu% and at the same time contro%%ing the

1/

access' se4era% techni$ues can be fo%%owed. The first one wou%d be to ma)e a method that returns fie%ds and others that assigns to it8 8rogram ,+ 3et and Det R >getset0.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 #.Jname/-C#.Jid/+#.J gpa/ end end ma)inar = Dtudent.new(%a)inar5=00=?F=?=5-.0<) puts ma)inar.name puts ma)inar. gpa ma)inar.set gpa -.G print)(7n) puts ma)inar Nutput+ %a)inar-.0< %a)inar-C=00=?F=?=+-.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. 5hate4er is +refi. with 3 after attrXreader' they become the accessor for that fie%d Gdro++ing the YH and writeab%e if attrXwriter is used. An e.am+%e is gi4en be%ow Gadd it u+ to the song.rb c%ass in the endH3

12

8rogram 2+ attr'reader and attr'writer >attrrw.rb@ lass Dong attr'writer +duration attr'reader +name5+duration end aDong = Dong.new(4Si ylops45 4Lle 945 <G=) aDong.duration = <F, puts aDong.name puts 4#.aDong.duration/4 Si ylops <F, 5e can a%so add 4irtua% attributes by not rea%%y returning or setting the 4ariab%es Oas is;8 Program ,: -irtual .ttribute [!irtattr.rb] Class Dong Ke) songRn%inutes= (Oalue) Jduration = Oalue/G=.to'i end end aDong = Dong.new(4Si ylops45 4Lle 945 <G=) aDong.sonRn%inutes = <F, puts aDong.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. "." Containers+ Iterators and ,loc-s AIt's a Bseful .ot,A said .ooh. ACere it is. And it's got 'A Dery Cappy ;irthday with love from .ooh' written on it. 3hat's what all that writing is. And it's for putting things in. 3here?A EA. A. Milne, $innie the .ooh Today we %oo) at objects whose on%y +ur+ose in %ife is to ho%d other objects. &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

remember. 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. The containers in Ruby are Arrays and ashes. *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.amined and changed. A Ruby array can ho%d any objects. Arrays grow as needed' just as strings do. @ew storage s%ots are created on demand' with nils inserted when necessary. Oeggies == >4 orn45 4lettu e45 4peas4@ Oeggies>F@ = 4sTuas"4 #now Oeggies be omes #> orn5lettu e5peas5nil5nil5sTuas"@ 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. sugar sa4es wear on our fingers and )eyboard. The w stands for words. 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 who%e +%ethora of Array o+erations are as fo%%ows3 1F

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- = a< 6 a0 #UC >4a45 4b45 4 45 0=5 <=5 -=@ a-.in ludeH (4b4) #UC true a0.in ludeH (4b4) #UC )alse a-.inde( (<=) #UC ? a-. 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. can be e.+ressed as an array of arrays' where each EinnerE array corres+onds to a row3
# ;"e matri( we want+ # 00 0< 0# 0? 0F 0G # 0, 02 01 m = > >0050<50-@5 >0?50F50G@5 >0,502501@ @

*u++ose we want the item in the %ast co%umn and first row. 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&:. ashes are another container bui%t in the Ruby %anguage. It;s methods are more or %ess as same as those of Array but the difference %ies within the inde. which is' for ash' any object.
" = 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

# " = .4$labama4=C4"umid45 4$las9a4=C4)rigid45 # 4Colorado4=C4ro 9y45 4Wis onsin4=C4 "eesy4/ ".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. If we %oo) u+ a )ey that doesnDt e.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 &>>. It;s the conce+t of b%oc)s and Iterators. (%oc)s are basica%%y name%ess functions' reminiscent of the Lambda form in LI*P or Python. (asica%%y' we can +ass a name%ess function to another function' and then that function can in4o)e the +assed8in name%ess function. 7or e.am+%e' a function cou%d +erform iteration by +assing one item at a time to the name%ess function. 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. Lis+ does it. Python does it .-4en & does it with function +ointers. 0any other %anguages do this sty%e of +rogramming. In Ruby' the difference is main%y a different )ind of synta. for higher order functions. In other %anguages' we ha4e to s+ecify e.+%icit%y that a function can acce+t another function as an argument. (ut in Ruby' any method can be ca%%ed with a b%oc) as an im+%icit argument. Inside the method' you can ca%% the b%oc) using the Oyie%d; )eyword with a 4a%ue. A Ruby iterator is sim+%y a method that can in4o)e a b%oc). At first sight' a b%oc) in Ruby %oo)s just %i)e a b%oc) in &' ?a4a' or Per%. 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. 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. *econd' the code in the b%oc) is not e.ecuted at the time it is encountered. Instead' Ruby remembers the conte.t in which the b%oc) a++ears Gthe %oca% 4ariab%es' the current object' and so onH' and then enters the method. This is where the magic starts. 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. 5hene4er a yie%d is e.ecuted' it in4o)es the code in the b%oc). 5hen the b%oc) e.its' contro% +ic)s bac) u+ immediate%y after the yie%d. ere is a tri4ia% e.am+%e8 Program 1/: (lo&0 a d $terator 1 [bl&0tr!.rb]

21

de) t"ree;imes yield yield yield end t"ree;imes . puts 4Hello4 / Output: Hello Hello Hello The b%oc) Gthe code between the bracesH is associated with the ca%% to the method threeTimes. 5ithin this method' yie%d is ca%%ed three times in a row. -ach time' it in4o)es the code in the b%oc)' and a cheery greeting is +rinted. 5hat ma)es b%oc)s interesting' howe4er' is that we can +ass +arameters to them and recei4e 4a%ues bac) from them. 7or e.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.rb] de) )ib:p;o(ma() i05 i< = 05 0 # parallel assignment w"ile i0 E= ma( yield i0 i05 i< = i<5 i06i< end end )ib:p;o(0==) . V)V print )5 4 4 / Output: 0 0 < - F 2 0- <0 -? FF 21 In this e.am+%e' the yie%d statement has a +arameter. This 4a%ue is +assed to the associated b%oc). In the definition of the b%oc)' the argument %ist a++ears between 4ertica% bars. 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. 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. (asica%%y' b%oc)s are designed for %oo+ abstraction. The most basic usage of b%oc)s is to %et us define your own way for iterating o4er the items. 7or e.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. (ut what if you want to iterate bac)wards from the end to the beginningR In &' we ha4e to set

22

u+ four things3 an inde.' a start 4a%ue' an end com+arison' and an increment. This is not good' because it re4ea%s interna% detai%s of the %ist. Ruby %et;s us hide that %ogic. (y using b%oc)s' we can hide the %oo+ %ogic inside the method or function. *o for e.am+%e by ca%%ing %ist.re4erseXeach ' we can do a re4erse iteration o4er the %ist without )nowing how the %ist is im+%emented on the inside. -4ery %anguage has a catch' the one that ma)es it harder for the newbies. 7or e.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+. And from out one month o%d e.+erience in Ruby' we can say that for Ruby' Iterators and b%oc)s were the com+%ications for us. Ies+ite the conce+t is c%ear' but the syntactic ru%es is not as c%ean as other features of Ruby. ".' .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. Ruby is an unty+ed %anguage' whate4er is ca%%ed standard ty+es here are actua%%y c%asses wra++ed u+. The basic ty+es that are under use in Ruby are8 /u bers Ruby su++orts integers and f%oating +oint numbers. Integers can be any %ength Gu+ to a ma.imum determined by the amount of free memory on your systemH. 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. 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. This +rocess is trans+arent' and Ruby automatica%%y manages the con4ersion bac) and forth. Program 12: umber.rb num = 2 ,.times do print num.type5 4 45 num5 47n4 num W= num end Li(num 2 Li(num G? Li(num ?=1G Li(num 0G,,,<0G Signum <20?,?1,G,0=GFG Signum ,1<<20G<F0?<G?--,F1-F?-1F=--G Signum G<,,0=0,-F-2GG2=,G-2-F,21?<-<=,GGG?0G0=<-FF????G?=-?F0<21G

2!

5e write integers using an o+tiona% %eading sign' an o+tiona% base indicator G= for octa%' =( for he.' or =b for binaryH' fo%%owed by a string of digits in the a++ro+riate base. 1nderscore characters are ignored in the digit string.
0<-?FG 0<-'?FG -F?0<-'?FG',21'0<-'-?F',21 =(aabb =-,, -=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.+onent is turned into a 7%oat object' corres+onding to the nati4e architectureDs doub%e data ty+e. Bou must fo%%ow the decima% +oint with a digit' as 1.e! tries to in4o)e the method e! in c%ass 7i.num. A%% numbers are objects' and res+ond to a 4ariety of messages. *o' un%i)e &> >' we find the abso%ute 4a%ue of a number by writing a@umber.abs' not absGa@umberH. Integers a%so su++ort se4era% usefu% iterators. 5eD4e seen one a%ready8 ,.times. 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+. Program 13: $ teger 2oopi g 3e&h i4ues [iloop.rb] -.times . print 4X 4 / 0.upto(F) . ViV print i5 4 4 / 11.downto(1F) . ViV print i5 4 4 / F=.step(2=5 F) . ViV print i5 4 4 / Output: X X X 0 < - ? F 11 12 1, 1G 1F F= FF G= GF ,= ,F 2= .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. *trings are objects of c%ass Dtring. *trings are often created using string %itera%s3 se$uences of characters between de%imiters. (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%. -ach is re+%aced with the corres+onding binary 4a%ue as the +rogram is com+i%ed. The ty+e of string de%imiter determines the degree of substitution +erformed. 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. 5hereas in the doub%e $uote a%% the esca+e character

2"

re+%acements as we%% as the 4ariab%e re+%acements are done. As an e.am+%e' if' in irb' we ty+e3 O-at at TUauthorV=;s; J-at at TUauthorV=sK Then the first one wi%% +rint -at at TUauthorV=;s whereas the second one wi%% yie%d' -at at 0afinar;s' +ro4ided that author 4ariab%e has the 4a%ue 0afinar. There are three more ways to construct string %itera%s3 IT' IY' and CChere documents.DD [$ and [\ start de%imited sing%e8 and doub%e8$uoted strings. [$A e%%o ThereA is e$ua4a%ent to O e%%o There; [\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;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;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. @orma%%y' this terminator must start in the first co%umn. owe4er' if you +ut a minus sign after the EE characters' you can indent the terminator. @OT-3 In this section' since the codes are e.treme%y tri4ia%' we wou%d be using the IR( interacti4e inter+reter for Ruby. 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. 7or e.am+%e' if' in irb' we ty+e +rintf J e%%o 5or%dK then in the immediate %ine. 5or)ing with Array and *trings is $uite simi%ar. 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%. -ach +osition in a string has a numerica% inde.. In good com+uter science tradition' RubyDs indices are counted starting with 6ero instead of one. *egments of a string' or substrings' are referred to by their starting +ositions and %engths. Putting this +air of numbers in s$uare brac)ets' we can e.amine or modify indi4idua% characters or %onger substrings.

2,

)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. The affected string e.+ands or contracts as needed.
)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.t8 to8%ast in +osition 82' and so on.
bar = )oo.up ase 6 bar>U050@ #UC bar>U,5?@ #UC bar>U,5?@ = 44 )oo.reOerse # bar == 4WPK3Pegdew4 4w4 43Peg4 # bar == 4WPKdew4

If we ta)e a %oo) at bar.methods and scan through the %ong %ist it gi4es you' weD%% see E9:E and E9:NE in there. 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. E9:E cou%d ha4e been ca%%ed EsubstringE or Es%iceE' and E9:NE cou%d ha4e been ca%%ed Ere+%aceXsubstring.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.
4ab 4.l[ust(,) #UC 4ab 4 4ab 4.r[ust(,) #UC 4 ab 4 4ab 4. enter(,) #UC 4 ab 4 4ab 4. enter(G) #UC 4 ab 4 (odd spa es go to t"e rig"t) 4ab 4. enter(<) #UC 4ab 4 (no "ange i) lengt" is too small)

count0descri&tion1

2/

Return the number of characters that match those in the descri+tion string. A range of characters can be s+ecified with a dash' as in 4a- 4.
s = 4ab de ab de4 s. ount(4 4) #UC < s. ount(4bUe4) #UC 2

delete0descri&tion1 Li)e ount' but return a co+y with a%% matching characters remo4ed.
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.


4aS 4aS 4aS 4aS 4.down ase #UC 4ab 4 4.up ase #UC 4$SC4 4.swap ase #UC 4$bC4 4. 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.
4Haysta 94.in ludeH(4needle4) #UC )alse 4Haysta 94.in ludeH(4sta4) #UC true 4Haysta 94.in ludeH(,<) #UC true (be ause HH is ,<)

inde40s&ec+ 5offset61 7ind the inde. where s+ec is found' starting either from the beginning or from offset. Again' s+ec can be either a string or a character.
4%ississippi4.inde((4ssi4) #UC < 4%ississippi4.inde((4ssi45-) #UC F 4%ississippi4.inde((4sp4) #UC nil (not )ound)

rinde40s&ec+ 5li it61 Li)e inde(' but find the %ast match instead of the first. The %imit sto+s the search.
4%ississippi4.rinde((4i4) #UC 0= 4%ississippi4.rinde((4i45G) #UC ?

stri&

22

Remo4e whites+ace Gin4isib%e characters such as s+aces' tabs' %inefeeds' and so forthH from the beginning and end.
4Prie Canal 7n4.strip #UC 4Prie Canal4

tr0s&ec+ re&l1 *hort for Etrans%ate.E Return a co+y with characters from s+ec re+%aced by the corres+onding characters from re+%. The first e.am+%e here simu%ates the down ase method.
4KND'LR&P.PX;4.tr(4$U\454aU!4) #UC 4dos')ile.e(t4 4%on9ey4.tr(4ymUT454NW+])H4) #UC 4%]+9eN4

This has been a rather e.hausti4e +art of the section. That is because *trings are not on%y a usefu% +art in Ruby +rogramming' but a%so in +rogramming in genera%. Ranges Ranges occur e4erywhere3 ?anuary to Iecember' 0 to F' rare to we%%8done' %ines ,0 through /2' and so on. If Ruby is to he%+ us mode% rea%ity' it seems natura% for it to su++ort these ranges. In fact' Ruby goes one better3 it actua%%y uses ranges to im+%ement three se+arate features3 se$uences' conditions' and inter4a%s. *ome interesting +oints regarding Ranges are as fo%%ows3 The first and +erha+s most natura% use of ranges is to e.+ress a se$uence. *e$uences ha4e a start +oint' an end +oint' and a way to +roduce successi4e 4a%ues in the se$uence. In Ruby' these se$uences are created using the J..K and J]K range o+erators. The two8dot form creates an inc%usi4e range' whi%e the three8dot form creates a range that e.c%udes the s+ecified high 4a%ue. (0..1).to'a #05 <5 -5 ?5 F5 G5 ,5 25 1@ (ZbarZ..ZbatZ).to'a #>4bar45 4bas45 4bat4@ As we%% as re+resenting se$uences' ranges may a%so be used as conditiona% e.+ressions. 7or e.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.
w"ile gets print i) /start/../end/ end

2M

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. This is done using ===' the case e$ua%ity o+erator. (0..0=) (0..0=) (0..0=) (ZaZ..Z[Z) (ZaZ..Z[Z) === === === === === F #true 0F #)alse -.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 -.+ressions. Regu%ar e.+ressions are used to match +atterns against strings. 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. Regu%ar e.+ressions are objects of ty+e Rege.+. They can be created by ca%%ing the constructor e.+%icit%y or by using the %itera% forms ApatternA and [r=pattern=. a = Mege(p.new(Z]7sW>a-!@Z) b = /]7sW>a-!@/ = Ir.]7sW>a-!@/ #/]7sW>a-!@/ #/]7sW>a-!@/ #/]7sW>a-!@/

Once you ha4e a regu%ar e.+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. The match o+erators are defined for both Dtring and Mege(p objects. If both o+erands of the match o+erator are Dtrings' the one on the right wi%% be con4erted to a regu%ar e.+ression. a a a a = 4Lats =^ /a/ =^ /!/ =^ 4ll4 Waller4 # 0 # nil # ,

The match o+erators return the character +osition at which the match occurred. They a%so ha4e the side effect of setting a who%e %oad of Ruby 4ariab%es. 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. 5e can use this to write a method' showR-' which i%%ustrates where a +articu%ar +attern matches. Program 1#: 5E [re.rb] de) s"owMP(a5re)

2F

i) a =^ re 4#._`/EE#._a/CC#._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 -.+ressions is a to+ic huge enough to deser4e its own +a+er and hence any further discussions. And a%ong with regu%ar e.+ressions' we end our discussion about the standard data ty+es of Ruby. ".8 74&ressions A%though some e.+ressions were co4ered in the section !.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 -.+ressions. 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. *ome to+ics about Ruby -.+ressions are %isted be%ow3 *tatements can be chained in Ruby a N bN c N dN e N , Things that are norma%%y statements in & or ?a4a are e.+ressions in Ruby. 7or e.am+%e' the i) and ase statements both return the 4a%ue of the %ast e.+ression e.ecuted. 7or e.am+%e8 song;ype = i) song.mp-;ype == %8-++ba!! i) song.written E Kate.new(01-F5 05 0) Dong++;radba!! else Dong++ba!! end else Dong++Nt"er end rating = ase OotesCast w"en =...0= t"en

!0

Mating++D9ip;"isNne w"en 0=...F= t"en Mating++CouldKoSetter else Mating++MaOe end In Ruby' many o+erators are actua%%y method ca%%s. 5hen you write aWb6 youDre actua%%y as)ing the object referenced by a to e.ecute the method CCWDD' +assing in the +arameter b. Bou then as) the object that resu%ts from that ca%cu%ation to e.ecute CC6DD' +assing as a +arameter. This is e.act%y e$ui4a%ent to writing8 Ga._GbHH.>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).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 =..`ls Ual` end Output: Calls t"e ls Ual t"ree times in a :#RX enOironment

Ruby has a sim+%e definition of truth. Any 4a%ue that is not ni% or the constant fa%se is true. Ruby su++orts a%% the standard boo%ean o+erators and introduces the new o+erator definedR. (oth JandK and J^^K e4a%uate to true on%y if both o+erands are true. They e4a%uate the second o+erand on%y if the first is true Gthis is sometimes )nown as Jshort8circuit e4a%uationKH. 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. They e4a%uate their second o+erand on%y if the first is fa%se. As with JandK' the on%y difference between CCorDD and CCaaDD is their +recedence. ?ust to ma)e %ife interesting' CCandDD and CCorDD ha4e the same +recedence' whi%e CC^^DD has a higher +recedence than JaaK. JnotK and JQKD return the o++osite of their o+erand Gfa%se if the o+erand is

!1

true' and true if the o+erand is fa%seH. And' yes' JnotK and JQK differ on%y in +recedence. The definedR o+erator returns ni% if its argument is not defined' otherwise it returns a descri+tion of that argument. If the argument is yie%d' definedR returns the string Dyie%dD if a code b%oc) is associated with the current conte.t. de)ineH 0 #dumy de)inedH %a)inar # onstant de)ined -.abs # met"od 5e ha4e a%ready gone through the conditiona% statement I7 ni a +re4ious section. In here we wou%d introduce the If o+erator which is much %i)e the same in Per%' the fo%%owing to e.+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. owe4er one was missed. 5hich is the 7or statement. 7or %oo+ ta)es a range and Iterates through it. Program 1, shows the 7or %oo+. ?ust %i)e &A?a4a' Obrea);';continue; and Ogoto; is a4ai%ab%e in Ruby as we%% in the form of Obrea);';ne.t; and Ogoto;. It additiona%%y introduces tow new )eywords Oredo; and Oretry;. Oretry; restarts the %oo+' whi%e Oredo; re+eats the current %oo+. (ui%t ins %i)e whi%e and for %oo+s don;t introduce any new sco+e.

".9 %odules 0odu%e is to Ruby is what names+ace is to &>>A&T. 5hen we write bigger codes the +robabi%ity of name c%ash increases. At times %i)e those' the conce+t of 0odu%es come to our rescue. Anything contained within the Cdef modu%e . . . end; enca+su%ates a modu%e.
module ;rig 8R = -.0?0F1<GF? de) ;rig.sin(() # .. end de) ;rig. os(() # .. end end

Any +rogram using this modu%e wi%% be %i)e8


reTuire 4trig4 y = ;rig.sin(;rig++8R/?)

!2

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

!!

List Processing3 Ruby has some LI*P %i)e features %i)e %ambda Gin the form of iterators and b%oc)sH. A%so the Array hand%ing ca+abi%ity of Ruby is e.treme%y +owerfu%. 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.t section discusses about the use of Ruby as a case +rogramming %anguage in &*& !2,. 8.0 Ruby as a Case *anguage for C.C "28 &*& !2, GProgramming Language Princi+%eH is the course for which this +a+er has been +re+ared for. And since this course dea%s with the different +rogramming %anguage' it is a%so e.+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%. Iifferent %anguages ha4e different features embedded in them. Lambda by LI*P and Python' Iterator by Ruby' Patterns by *ma%%ta%) are on%y a few to mention. It is' to our minds' im+erati4e to inc%ude those features in a %anguage course %i)e !2,' 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. Instead of Python' Ruby can be tought to introduce us to a mu%ti8+ur+ose c%ean %anguage. Instead of Per%' Ruby can be taught to +ro4ide us with the f%e.ibi%ity or te.t mani+u%ation. The reason *ma%%ta%) or -iffe% cou%d be usefu% is the same reason Ruby can be taught. Ruby is as object oriented as *ma%%ta%)' and inf%uenced by the synta. of -iffe%. 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. 7or a case %anguage in &*& !2, or simi%ar +rogramming %anguage course' Ruby can be the best se%ection. 9.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. 5e +ic)ed Ruby because we wanted a change. Ruby' a%though object oriented in +aradigm' and scri+ting %anguage in nature' +ro4ides us with an en4ironment we ne4er seen before. 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. 5ith an e.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. In (ang%adesh' few +rogrammers e4en )now the name Ruby as a +rogramming %anguage.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.

!"

;.0 A&&endi4 I: ,ibliogra&hy 516 (a a. <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@. A=ailable online in: htt&:AAwww.rubygarden.orgAfa)A

!,

S-ar putea să vă placă și