fsf - i love ruby - 2012
Post on 07-Jul-2018
216 Views
Preview:
TRANSCRIPT
-
8/18/2019 FSF - I Love Ruby - 2012
1/170
I Love Ruby 2012 Edition
1
-
8/18/2019 FSF - I Love Ruby - 2012
2/170
I Love Ruby 2012 Edition
Contents
I love Ruby.......................................................4Copyright..........................................................5
I........................................................................6Kannan Doss.....................................................6Jawahar.............................................................7Pre!han"ar.....................................................7#ai"ev...............................................................$%etting this boo&..............................................'
%etting e(aple progras...........................'Installing Ruby...............................................1)
Installing Ruby on *buntu %+*,-inu(....1)Installing on in"ows...............................11Installing on /a!.......................................11
Installing ID0.............................................11nline Resour!es............................................12
Ruby ebsite.............................................12Ruby 3oru...............................................12witter........................................................12
%etting #tarte"................................................14Intera!tive Ruby.........................................14Doing soe /ath......................................14
#pa!e "oesnt atter..............................16De!ials................................................17
ariables....................................................17+aing Convention..............................1'he un"ers!ore a spe!ial variable......1'
Constants....................................................2)#trings........................................................21
#tring 3un!tions....................................220s!ape se8uen!e....................................29
*sing e(t 0"itor.......................................24Printing #oething....................................25%etting Input..............................................25Coents..................................................26
Coparison an" -ogi!..................................2'-ogi!al perators......................................2'
true :; .................................................................91i> else..........................................................91elsi>............................................................92unless.........................................................99unless else..................................................99!ase when...................................................94? @...............................................................97
-oops..............................................................9$
"ownto.......................................................9$
ties...........................................................9'upto............................................................4)
step.............................................................41while..........................................................42until............................................................49brea&..........................................................44
Arrays.............................................................45/ore on Array............................................47#et operations.............................................4'
Bashes an" #ybols.......................................51De>ault values in Bash...............................52-ooping hashes.........................................52/ore way o> hash !reation........................59
*sing sybols...........................................54Ranges............................................................5$
Ranges use" in !ase .. when.......................5'Che!&ing Intervals.....................................6)*sing triple "ots ...................................61
3un!tions........................................................62Arguent Passing......................................69De>ault Arguent......................................64Returning alues........................................65Re!ursive >un!tion.....................................66
ariable #!ope................................................6$%lobal ariables.........................................7)Classes bEe!ts...........................................74
Creating a #8uare.......................................743un!tions in Class......................................75InitialiFers or Constru!tors........................76Private /etho"s.........................................77Class variables an" etho"s......................7'Inheritan!e.................................................$1verri"ing /etho"s...................................$9he super >un!tion.....................................$5
0(ten"ing !lass..........................................$7Re>le!tion...................................................$$0n!apsulation.............................................'1Polyorphis............................................'9Class Constants..........................................'4
/o"ules an" /i(ins.......................................'7Calling >un!tions without in!lu"e..............''Classes in o"ules...................................1)9/i(ins......................................................1)4
#hebang........................................................1)7Date an" ie..............................................1)$
Days between two "ays............................11)
2
-
8/18/2019 FSF - I Love Ruby - 2012
3/170
I Love Ruby 2012 Edition
Bow any "ays have you live"?.............1113iles..............................................................114
#toring output into >iles...........................114a&ing >ile as input...................................114
3ile !opy a &in" o>................................115Displaying a >ile.......................................116Rea"ing >ile line by line ..........................117pen an" new the "i>>eren!e................117De>ining our own line en"ings.................11'Rea"ing byte by byte...............................12)Rea"ing single !hara!ter at a tie...........12)Renaing >iles.........................................1213in"ing out position in a >ile....................121riting into >iles......................................129Appen"ing !ontent into >iles....................125
#toring obEe!ts into >iles..........................126Pstore...................................................126GA/-.................................................12'
Pro! an" Hlo!&s............................................199Passing paraeters...................................194Passing Pro! to etho"s..........................194Returning Pro! >ro >un!tion..................195
/ulti hrea"ing............................................197#!ope o> threa" variables.........................14)hrea" 0(!lusion.....................................141
Dea"lo!&s................................................144hrea" 0(!eption.....................................146hrea" Class /etho"s.............................14$hrea" Instan!e /etho"s.........................14'
Regular 0(pressions.....................................151Creating a epty rege(p..........................151Dete!ting Patterns....................................151hings to reeber.................................152he "ot.....................................................159Chara!ter !lasses......................................159#!anning..................................................155Captures...................................................157/at!hData !lass.......................................16)An!hors an" Assertions ..........................161
An!hors...............................................161
Assertions............................................162Ignoring Cases.........................................164Ignore #pa!es...........................................164
3inal or"....................................................1653or 2)12 0"ition......................................1653or 2)1) 0"ition......................................165
*n"ers!ore....................................................167An iportant /ath Dis!overy......................16$#ponsors.......................................................16'
9
-
8/18/2019 FSF - I Love Ruby - 2012
4/170
I Love Ruby 2012 Edition
I love Ruby
Ruby is easy to learn prograing language it was invente" by a guy nae" /atF in Japan. Ruby
is a >ree1 so>tware an" !an be use" by any one >or no !ost. Rubys popularity was initially !on>ine"
to Japan later it slowly tri!&le" out to rest o> the worl". hings !hange" with the eergen!e o>
Ruby on Rails whi!h is a popular web"evelopent >raewor& thats written with Ruby.
I was thrille" when I starte" to progra in Ruby. ne o> the >irst appli!ation was a stu"ent ran&ing
so>tware >or y o who was a tea!her. I was able to write the !onsole base" appli!ation in Eust 92
lines. his opene" y eyes an" a"e e realiFe the power o> Ruby. he language was siple easy
to learn an" nearly per>e!t. Currently I a an pro>essional Ruby on Rails prograer hea"ing a
!osing tea in a !opany ebto"ay Husiness.
his boo& is written >or *buntu %+*,-inu( users its be!ause I thin& *buntu will !on8uer "es&tops
o> prograers in near >uture. Alost all who have Debian %+*,-inu( base" "istro shoul" >eel at
hoe while trying to learn Ruby using this boo&. I> you are using other operating systes li&e
#olaris # or in"ows please !onta!t your perating #yste help !hannels to learn how to
install or get starte" with Ruby. Gou !an also visit http@,,rubylang.org to learn an" how get starte"
with Ruby.
1 3ree here "oes not ean Fero !ost. isit http@,,>s>.org to &now ore
4
http://ruby-lang.org/http://fsf.org/http://fsf.org/http://fsf.org/http://ruby-lang.org/
-
8/18/2019 FSF - I Love Ruby - 2012
5/170
I Love Ruby 2012 Edition
Copyright
Copyright (c) 2009 - 2012 Bigbang to Infinite !arthi"eyan # !
Perission is grante" to !opy "istribute an",or o"i>y this "o!uent un"er the ters o> the %+*
3ree Do!uentation -i!ense ersion 1.9 or any later version publishe" by the 3ree #o>tware
3oun"ationL with no Invariant #e!tions no 3rontCover e(ts an" no Ha!&Cover e(ts. A !opy o>
the li!ense !an be >oun" in http@,,www.gnu.org,!opyle>t,>"l.htl
5
http://www.gnu.org/copyleft/fdl.htmlhttp://www.gnu.org/copyleft/fdl.html
-
8/18/2019 FSF - I Love Ruby - 2012
6/170
I Love Ruby 2012 Edition
I
Bi I a A.K.Karthi&eyan the author o> this boo&. I !ae
a!ross Ruby an" >oun" that the language was "aFFling. I
thought why not write a boo& >or sel> stu"y an" so was
!reate" this boo&.
Currently I a an web prograer I use Ruby on Rails "ue
to its great innovative >eatures. Gou !an !onta!t e at
in"aslabMgail.!o or tweet to M&arthi&Na&
his boo& is no at!h to other Ruby best sellers this is Eust
an attept to have a personaliFe" Ruby stu"y aterial.
Kannan Doss
I a very u!h grate>ul Kannan Doss who wor&e" in /in"
As -ab as a apprenti!e web "eveloper an" a Ruby on Rails
%ee& >or putting sin!ere e>>orts to iprove the 8uality o> this
boo&. Be has proo> rea" the entire boo& spotte" ista&es he
!oul" >in" !ataloge" the an" !orre!te" the.
ithout hi the boo& wont be a goo" 8uality as it is now. I
a not saying that this boo& is superb. Hut his e>>orts truly
playe" a "e!isive role to a&e this boo& what it is.
Gou !an !onta!t Kannan at "oss.&annanMgail.!o
6
mailto:mindaslab@gmail.commailto:doss.kannan@gmail.commailto:mindaslab@gmail.commailto:doss.kannan@gmail.com
-
8/18/2019 FSF - I Love Ruby - 2012
7/170
I Love Ruby 2012 Edition
Jawahar
Jawahar trains in ebto"ay business has goo" anageent
s&ills. Be is also ta&ing part in I -ove Ruby O>a!eboo&
group propagan"a. I a happy that he is !ontributing his
e>>orts to this boo&. Jawahar gra"uate" >ro #atyabaa
*niversity in the "is!ipline In>oration e!hnology
0ngineering.
Gou !an !onta!t hi at@ Eawahar.!s9Mgail.!o
Premchandar
Pre!han"er thin&s an" wor&s li&e a s!ientist. Be soe how
>in"s right solutions >or any probles an" at ties soe
how lin&s Ruby prograing with worholes an" other
stu>>. Be trains in ebto"ay Husiness as a Rails prograer.
Pre gra"uate" >ro elt!h Chennai in the "is!ipline o>
0le!troni!s an" Couni!ation 0ngineering.
Gou !an !onta!t hi at@ pre!sp!Mgail.!o
7
mailto:jawahar.cs3@gmail.commailto:jawahar.cs3@gmail.commailto:premcspc@gmail.commailto:premcspc@gmail.commailto:jawahar.cs3@gmail.commailto:premcspc@gmail.com
-
8/18/2019 FSF - I Love Ruby - 2012
8/170
I Love Ruby 2012 Edition
Saidev
#ai"ev wor&s in ebto"ay Husiness as a Rails "eveloper. Be
!oul" be!oe a Ruby an" Rails Je"i i> he wishes. Be
gra"uate" >ro Capus o> %uin"y Annauniversity in the
"is!ipline o> Coputer #!ien!e 0ngineering an" helpe" to
spot any ista&es in this boo&.
Be !an be !onta!te" at@ saiMwebto"aybusiness.!o
$
mailto:sai@webtodaybusiness.commailto:sai@webtodaybusiness.com
-
8/18/2019 FSF - I Love Ruby - 2012
9/170
I Love Ruby 2012 Edition
Getting this book
his boo& is now hoste" in http@,,is.g",r2)12 . All announ!eents about this boo& are available in
>a!eboo& in this *R-@ https@,,www.>a!eboo&.!o,pages,Iloveruby,17226'54'4517)5 there is no
ne!essity >or you to have >a!eboo& a!!ount to a!!ess this page.
Getting example programs
he e(aple progras in this boo& are hoste" in %ithub in the >ollowing *R-@
https@,,github.!o,in"aslab,ilr( . I realiFe any who rea" this boo& are starters who have Eust
plunge" into prograing. Ben!e you !an "ownloa" all e(aples by !li!&ing this lin&@
https@,,github.!o,in"aslab,ilr(,Fipball,aster
'
http://is.gd/r2012https://www.facebook.com/pages/I-love-ruby/172269549451705https://github.com/mindaslab/ilrxhttps://github.com/mindaslab/ilrx/zipball/masterhttps://github.com/mindaslab/ilrx/zipball/masterhttp://is.gd/r2012https://www.facebook.com/pages/I-love-ruby/172269549451705https://github.com/mindaslab/ilrxhttps://github.com/mindaslab/ilrx/zipball/master
-
8/18/2019 FSF - I Love Ruby - 2012
10/170
I Love Ruby 2012 Edition
Installing
Ruby
Installing Ruby on Ubuntu GNU/Linux
&ay you nee" to install a thing !alle" R/ Oruby version anager whi!h will !ontrol whi!h
version you are using. hy? Its be!ause ruby version !hanges >ast. He>ore you ha" 1.$ now 1.' an"
soon ruby 2 will be out. Apart >ro Eust using ruby you will also use it >or other stu>> li&e web
"evelopent li&e #inatra an" Ruby on Rails. Gou ight nee" to !hange >ro one version to other
without uninstalling an" reinstalling ruby again an" again. R/ anages this >or you. ith siple
!oan"s we !an swit!h between Ruby versions easily.
Installing RVM :
K to install R/ you nee"to a&e sure you have the ne!essary libraries to !opile an" install it.
#o !opy the stu>> below Ooitting the starting Q an" paste it into terinal
I> you are using the PD3 version o> this boo& !opying an" pasting these !o"es will result in an
error so I have put all the !o"es in this >ile ruby_install.bash use it to avoi" te"ious typing
$ sudo apt-get install build-essential bison openssl libreadline6 libreadline6-
dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0
libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev
automake
+ow install R/ using the >ollowing !oan"
$ curl -L https://get.rvm.io | bash -s stable --ruby
n!e "one give these !oan"s into terinal. hese will tell *buntu %+* , -inu( where to >in"
the ruby interpreter.
$ echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load
RVM function' >> ~/.bashrc
$ source ~/.bashrc
n!e "one possibly restart !oputer an" in terinal type the >ollowing
$ ruby -v
It will spit an output soethin li&e this
1)
https://raw.github.com/mindaslab/ilrx/master/ruby_install.bashhttps://raw.github.com/mindaslab/ilrx/master/ruby_install.bashhttps://raw.github.com/mindaslab/ilrx/master/ruby_install.bash
-
8/18/2019 FSF - I Love Ruby - 2012
11/170
I Love Ruby 2012 Edition
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
hen all is K:
Installing on WindowsBA? * thin& I a insane to use in"ows now?
Installing on Mac
Heauty is Eust s&in "eep. nly stupi"s will get se"u!e" by it. I> you are using a! brea& >ree >ro it
an" try out %+*,-inu( whi!h is ro!& soli" an" DR/ >ree.
Installing IDEGou nee" a goo" ID0 OIntegrate" "evelopent environent to get starte" with Ruby. I re!oen"
siple an" light weight ID0 %eany2. In *buntu a!hine Eust type
sudo apt-get install geany
>or the ID0 to get installe". I> the syste as&s >or a"inistrator passwor" provi"e it.
Cli!& the "ash button an" type in geany. Cli!& on the geany i!on you will get it @
2 in"ows users goto http@,,www.geany.org, to "ownloa" the installer
11
http://www.geany.org/http://www.geany.org/
-
8/18/2019 FSF - I Love Ruby - 2012
12/170
I Love Ruby 2012 Edition
nline Resources
Ruby has got a e(!ellent online !ounity o> ha!&ers who are rea"y to help alost any one who
has alost any "oubt about Ruby. hey love the prograing language an" want others to love an"
e(perien!e it too. Ruby is a great prograing language that will put soething goo" in your heart.
n!e you have learne" it an" start to intera!t with >ellow ha!&ers you will naturally ten" to help
others. #o "o visit the websites re!oen"e" in this se!tion. hey ight be o> great use to you.
Ruby Website*R-@ http@,,rubylang.org
Ruby website is a great pla!e to start with Ruby. It provi"es you with the installers to install Ruby
on your operating syste. It has !ool lin&s li&e ry Ruby: in your browser whi!h lets you try out
Ruby right >ro your web browser an" a lin& !alle" Ruby in wenty /inutes tea!hes you basi!s o>
Ruby prograing. Ruby is su!h a siple language that you Eust nee" 2) inutes to grasp it: rust
e its true:
Ruby orum*R-@ http@,,www.ruby>oru.!o,
#o where to go i> you have "oubts with Ruby? Gou !an visit http@,,www.ruby>oru.!o, whi!h is
a website thats nothing but !olle!tion o> Ruby >orus an" !ontains lot o> 8uestion an" answers
about Ruby. +o atter how stupi" it ay be you !an post your 8uestion. A &in" enough gentle an
Oor a la"y i> you are lu!&y will answer it. 3or the sa&e o> heaven never >ail to as& 8uestions. he
"i>>eren!e between a goo" an" great prograer !oul" be Eust a 8uestion you as&.
!witter*R-@ http@,,twitter.!o
witter is a so!ialiFing website. hen why on 0arth a I putting it here. ell lot o> Ruby
prograers use twitter possibly be!ause its written with Ruby. o &now the latest news about
-
8/18/2019 FSF - I Love Ruby - 2012
13/170
I Love Ruby 2012 Edition
about Ruby language. ry sear!hes li&e
-
8/18/2019 FSF - I Love Ruby - 2012
14/170
I Love Ruby 2012 Edition
Getting Started
Baving installe" the nee"e" so>tware lets gets starte".
Interacti"e Ruby
Ruby provi"es us a easy way to intera!t with it this >eature is !alle" intera!tive ruby or irb. ith irb
you !an type sall bits o> ruby !o"e in your !onsole an" see it get e(e!ute". irb is a great tool to
!he!& out sall pie!es o> Ruby !o"e. In your terinal type irb or irb –-simple-prompt you
will be getting propt as shown
irb(main):001:0>
he above propt will be got i> you ha" type" irb
>>
he above propt will be got i> you ha" type" irb –-simple-prompt in e(aples >ro now on I
will be using the siple propt as its siple >or e to write in this boo&. -ets write our >irst hello
worl" progra in the propt type the >ollowing O"ont type those>>
>> puts 'Hello World!'
hen you press enter you will get output as >ollows. In Ruby puts is use" >or printing soe thing
onto the !onsole.
Hello World !
=> nil
ery well we have !oplete" our hello worl" progra un"er a inute. -ets !he!& what is 56 to the
power o> 91
>> 56**31=> 1562531701075863192779448904272185314811647640213651456
P#: Gou never thought it woul" be su!h a large nuber "i" you? Any way the ** is use" to >in"
a nuber raise" to the power o> another nuber.
o 8uit irb an" return to noral !onsole or terinal propt type quit
Doing some Mat#
Coputer is a "evi!e that !oputes or "oes soe ath. ith irb we !an "o easy ath. I> you
14
-
8/18/2019 FSF - I Love Ruby - 2012
15/170
I Love Ruby 2012 Edition
"ont li&e to wor& with nubers ruby !an "o it >or you. #o >irst lets a"" these nubers @ 1 45 67
$'972 56 an" 12$. o "o so in your irb propt Eust type these nubers separate" by a plus
sign an" you will get the result
>> 1 + 45 + 67 + 893 + 72 + 56 + -128
=> 1006
Bere are soe !oon ath operators that you will >in" use>ul
perator hat they "o
+ A""s nubers
- #ubtra!ts a nuber >ro another nuber
/ Divi"es a nuber with another nuber
* /ultiplies two nubers
** 3in"s a nuber raise" to the power o> another
% 3in"s the reain"er
+= A""s an" assigns a value to a variable
-= #ubtra!ts an" assigns a value to a variable
*= /ultiply an" assigns a value to a variable
/= Divi"es an" assigns a value to a variable
%= 3in"s the reain"er an" assigns it to a variable
Addition Example: -ets say that I want to a"" 56 an" 72 an" >in" its result I !an "o it as shown@
>> 56+72
=> 128
Subtraction Example: In this e(aple I a subtra!ting 64 >ro 112
>> 112-64
=> 48
Division Example: -ets say I want to "ivi"e 117 by12 an" >in" the 8uotient I !an "o in Ruby li&e
this
>> 117/12
=> 9
Power Example: -ets say I want to >in" what we will get by !ubing >ive O>ive raise" to the power
o> three I !an "o it in Ruby as shown
>> 5**3
=> 125
Modulus or Remainder Example: I want to &now what we will get as reain"er when we "ivi"e
21 by 4 I !an "o it as shown
15
-
8/18/2019 FSF - I Love Ruby - 2012
16/170
I Love Ruby 2012 Edition
>> 21%4
=> 1
Addition with assignment Example: -ets "e!lare a variable i set it to Fero an" a"" 24 to it. In
ruby you !an "o it as shown
>> i = 0
=> 0
>> i+=24
=> 24
>> i
=> 24
At the en" when we type i an" see we get 24. his eans i hol"s the value 24 in it.
Subtraction with assignment Example: -ets "e!lare a variable j assign it with a value 5) an"
ta&e away 17 >ro it
>> j = 50
=> 50
>> j -= 17
=> 33
>> j
=> 33
At the en" when we type j an" see we get 99. his eans j hol"s the value 99 in it.
Multiplication with assignment Example: -ets "e!lare a variable k set it to 9 an" ultiply it by
nine
>> k = 3=> 3
>> k *= 9
=> 27
>> k
=> 27
At the en" when we type k an" see we get 27. his eans k hol"s the value 27 in it.
Division with assignment Example: -ets "e!lare a variable s set it to 25 an" "ivi"e it by 5
>> s = 25
=> 25
>> s /= 5=> 5
>> s
=> 5
At the en" when we type s an" see we get 5. his eans s hol"s the value 5 in it.
ry other operators on your own I running out o> patien!e.
$pace doe%n&t 'atter
-ets say that I want to a"" 54 with 62 how !an I !oan" irb to "o it. #houl" it be 54+62 or !an I
16
-
8/18/2019 FSF - I Love Ruby - 2012
17/170
I Love Ruby 2012 Edition
leave spa!es so that !o"e !oul" be neatly written li&e 54 + 62 . ell >ortunately in Ruby leaving
spa!es "oesnt really atter you !an give it in any nuber o> ways as shown below an" still get the
sae result.
>> 54+62
=> 116
>> 54 +62
=> 116
>> 54+ 62
=> 116
>> 54 + 62
=> 116
>> 54 + 62
=> 116
+oti!e that the plus weather it sti!&s with 54 or 62 or has spa!e between the no atter how long
the spa!e is it prints out the right result.
(eci'a)%
hen you "ivi"e 5 by 9 in ruby you get result as >ollows
>> 5/3
=> 1
In other wor"s it gives the 8uotient. In reality 5 "ivi"e" by 9 is alost 1.666666666666666667 so
how to get this answer? he truth is 5 an" 9 are integers or nubers that "ont have "e!ial part. I>
you want a >airly a!!urate answer you !an rephrase your !oan" to Ruby as >ollows
>> 5.0/3
=> 1.66666666666667
In the above way we are spe!i>ying 5.) instea" o> 5 in other wor"s we are >or!ing Ruby to a&e a
>loating point or "e!ial !al!ulation instea" o> integer !al!ulation. his a&es Ruby to give an
>airly a!!urate answer.
$ariables
ariables are soething that stores value in it. Gou !an iagine the as a bo( whi!h !an hol"
pebbles. I> a bo( nae" a hol"s >ive pebbles then its value is 5 i> another bo( b hol"s 9 pebbles
then its value is three. -et say you get an new bo( !alle" c an" you want its value to be the su o>
bo( a an" bo( b then you siply a"" nuber o> pebbles in a an" b it totals to $ you put $ pebbles
in ! to a&e c = a+b. I hope you have got a hint what a variable is. -ets progra it in Ruby
>> a = 5
=> 5
>> b = 3=> 3
17
-
8/18/2019 FSF - I Love Ruby - 2012
18/170
I Love Ruby 2012 Edition
>> c = a+b
=> 8
-ets try another proble I buy 5) angoes >ro a >arer at Rs 1), an" bring it to the ar&et an"
sell it at Rs 15, ea!h what is y pro>it.
Answer@
K >irst I have 5) angoes so in irb I type as >ollows@
>> mangoes = 50
=> 50
#o I have assigne" the value o> 50 to a variable mangoes. +e(t I "e!lare an" assign a value o> 10 to
a variable buy_price as shown@
>> buy_price = 10
=> 10
In a siilar >ashion I assign 15 to a variable nae" sell_price
>> sell_price = 15
=> 15
+ow pro>it per ango is the "i>>eren!e between sell an" buy pri!e hen!e I !an !al!ulate it as shown
>> profit = sell_price - buy_price
=> 5
Hy selling a ango I get a pro>it o> Rs 5, what will I get by selling 5) angoes? Its a ultiple o>
profit with mangoes an" we get it as shown
>> total_profit = profit * mangoes
=> 250
#o by selling 5) angoes we !an earn a pro>it o> Rs 25),. -ets say that we have bought 72
angoes now we want to &now what pro>it woul" be this !an be easily "one by !hanging or
varying the value mangoes >ro 5) to 72 an" re!al!ulating the total_profit as shown below
>> mangoes = 72
>> total_profit = profit * mangoes
=> 360
+ow you ay &now why we !all these things are variables a variable is a bo( that !an !ontain any
value it wants. Just li&e you !an a"" or ta&e away pebbles >ro a bo( you !an "o the sae to
variables.
1$
-
8/18/2019 FSF - I Love Ruby - 2012
19/170
I Love Ruby 2012 Edition
*a'ing Convention
In the ango e(aple you woul" have noti!e" that I have given the naes o> variables as
buy_price sell_price total_profit an" not as buy price sell price total profit why
so? It turns out that one ust >ollow a !ertain naing !onvention or rules when naing a variable.
he rules o> naing a variable are as >ollows
1. here ust be no spa!e in between variable naes
2. here ust be no spe!ial !hara!ter e(!ept un"ers!ore N in a variable nae
9. A variable nae !an have nubers
1. A variable nae ust not start with a nuber
4. A variable ust either start with a !hara!ter or an un"ers!ore
1. Capital !hara!ter shoul" not appear at the start o> variable
Helow given are e(aples o> vali" variable naes
mango
total_price
mango_
_mango
buyPrice
boeing747
boeing_747
iam23yrsold
Helow are given e(aples o> invali" variable naes
34signals
Mango
total cost
+he under%core , a %pecia ) var iab)e
#uppose we want to >in" whats $7 raise" to the power 12 we !an "o as >ollows
>> 87**12
=> 188031682201497672618081
+ow we want to ultiply the result with 5 an" see the answer now the above result is a whopy 24
"igit nuber an" we ust type all o> it an" put a star >ive to get an answer thats a lot o> wor&: I>
you are a prograer laFiness shoul" >low in your veins otherwise >in" another pro>ession. ne
way is to assign this value to a variable an" ultiply it by 5 as shown below
>> a = 87 ** 12
=> 188031682201497672618081
1'
-
8/18/2019 FSF - I Love Ruby - 2012
20/170
I Love Ruby 2012 Edition
>> a*5
=> 940158411007488363090405
o.ever there i% another ea%y .ay a% %ho.n beo.
>> 87**12
=> 188031682201497672618081
>> _*5=> 940158411007488363090405
I "i" >in" out $7 raise" to the power o> 12 an" a>ter that I ultiplies un"ers!ore N with >ive: Hut
how !oe? *n"ers!ore is a spe!ial &in" o> variable in it the result o> last e(e!ution gets store"
autoati!ally. I> you want to use the last obtaine" output you !an "o so by using un"ers!ore N as a
variable9.
%onstants
*nli&e variables soe values ust be !onstant >or e(aple the ra"ius o> the 0arth is !onstant the
spee" o> light is !onstant. In probles that "eal with these &in" o> issues or in situations where you
are absolutely !ertain that soe values wont !hange you !an use !onstants.
A !onstant !an be thought as a variable whos value "oesnt !hange. Constants in Ruby starts with a
!apital letter it !oul" then be >ollowe" by alphabets nubers an" un"ers!ore. -ets now have a
!onstant !alle" Pi who value will be e8ual to atheati!al pi to "o so Eust type the >ollowing
in irb propt
>> Pi = 3.1428
=> 3.1428
Baving assigne" the value o> to a !onstant nae" Pi we will now try to >in" area a !ir!le
whose ra"ius is 7 units so lets use our >aith>ul !al!ulator the irb. e &now that ra"ius o> a !ir!le is
r2 4 where r is the !ir!les ra"ius. In your irb propt we !an "o the !al!ulation as >ollows
>> r = 7
=> 7
>> Pi*r**2
=> 153.9972
#o we >in" area o> !ir!le is roughly 159.''72 s8uare units whi!h is very near to the e(a!t value o>
154 s8uare units.
ne !an as& weather !an we !hange value o> !onstant? I "ont say its ipossible but i> we !hange
ruby gives us warning that we are !hanging the value o> a !onstant a>ter the warning the !onstant
gets !hange" anyway.
9 his un"ers!ore as a variable wor&s only in intera!tive ruby Oirb. hen you are e(e!uting a ruby progra type" in
a >ile this won& wor&. #ee se!tion *n"ers!ore in Appen"i(4 ell I &new it be!ause Albert 0instien is y >rien". I Eust tal&e" to hi an" he tol" e the >orula >or area o> !ir!le
2)
-
8/18/2019 FSF - I Love Ruby - 2012
21/170
I Love Ruby 2012 Edition
>> Pi=5
(irb):35: warning: already initialized constant Pi
=> 5
In the above e(aple I have re assigne" the value o> Pi to 5 as you !an see in the se!on" line Ruby
interpreter "oes throws out a warning that Pi is alrea"y initialiFe" !onstant but any way the value o>
Pi gets !hange" to 5. It is strongly "is!ourage" not to !hange values o> !onstants in pro>essional
prograing.
&trings
ill now we have seen about nubers now lets see soething about te(t. In !oputers te(t are
!alle" as string5. K lets see about strings in Ruby. -ets start with an hello worl". In your irb type
hello worl" as shown
>> "hello world"
=> "hello world"
As a response you get an “hello world” . In short string is any stu>> thats surroun"e" by < or by
+ow lets try the above e(aple by surroun"ing the above hello worl" with single 8uotes
>> 'hello world'
=> "hello world"
ell you "o get the sae response. #o whats the "i>>eren!e between single an" "ouble 8uotes? a&e
a loo& at the >ollowing e(aple
>> time_now = Time.new # Get the current time into a variable
=> Fri Jan 15 16:43:31 +0530 2010
>> "Hello world, the time is now #{time_now}"
=> "Hello world, the time is now Fri Jan 15 16:43:31 +0530 2010"
>> 'Hello world, the time is now #{time_now}'
=> "Hello world, the time is now \#{time_now}"
At >irst we "e!lare a variable !alle" time_now an" store the !urrent tie into it. he !urrent tie in
Ruby is got by Time.new !oan". +ow we have a variable an" we !an ebe" it into a string by
putting it li&e#{put_your_variable_here}
. #o we want to tell the worl" the tie now issoething so we give a !oan" as shown
>> "Hello world, the time is now #{time_now}"
=> "Hello world, the time is now Fri Jan 15 16:43:31 +0530 2010"
an" we get a proper result. +ote that you have en!lose" the string with a "ouble 8uotes. +ow lets
try the sae thing with single 8uotes
>> 'Hello world, the time is now #{time_now}'
=> "Hello world, the time is now \#{time_now}"
e see that in this !ase the worl" is not able to see what tie it is rather its able to see a ugly string
5 Possibly be!ause they are string o> !hara!ters
21
-
8/18/2019 FSF - I Love Ruby - 2012
22/170
I Love Ruby 2012 Edition
as shown
"Hello world, the time is now \#{time_now}"
hat ever thats put between single 8uotes gets printe" as it is. Gou ight as& why # is printe"
as \# well we will see it in es!ape se8uen!e soon.
$tr ing /unct ion%
here are !ertain !ool things you !an "o with a string with the built in >un!tions an" routines pa!&e"
into Ruby. 3or e(aple i> I want to >in" the length o> a string I !an use the length >un!tion as shown
>> "my name is billa".length
=> 16
here are any >un!tions soe o> whi!h are given in the table shown. I ust warn you that this
table is not !oprehensive you ust !he!& the Ruby "o!uentation6 >or a !oprehensive
!overage.
Input 'utput Notes
"my name is billa".length 16 he length >un!tion >in"s thelength o> a string
"my name is billa".reverse allib si eman ym he reverse >un!tionreverses a string
"my name is billa".capitalize My name is billa CapitaliFes the given string
"my name is billa".upcase MY NAME IS BILLA Converts lower !ase!hara!ters to upper!ase
"MY NAME IS BILLA".downcase my name is billa Converts upper!ase!hara!ters to lower !ase
"my name is billa".next my name is billb his is 8uiet illogi!al >un!tionthat prints the ne(t logi!al#tring
"my name is billa".empty? false Returns true i> string isepty else returns false
"".empty? TRUE Returns true i> string isepty else returns false
K so we have seen soe >un!tions lets now see what operations !an be per>ore" on string. he
6
22
-
8/18/2019 FSF - I Love Ruby - 2012
23/170
I Love Ruby 2012 Edition
>irst one is !on!atenation in whi!h two or ore strings !an be Eoine" together ta&e a loo& at
e(aple below
>> "Hello"+" "+"World!"
=> "Hello World!"In the !o"e above I have Eoine" three strings > : An" here is your result
=> "OM OM OM OM OM OM OM OM OM OM "
he ultipli!ation operator >ollowe" by a nuber prints a string + nuber o> ties where + is the
nuber given a>ter S.
E%cape %e0uence
henever you type a stateent li&e puts “Hello World!” the Ruby interpreter prints Hello
World!. hat is every thing between < an" < gets printe". ell not always. here are soe things
that you !an put between < an" < that will es!ape the noral printing se8uen!e. -aun!h your irb an"
type the e(aple given below@
>> puts "Hello \r World!"
World!
=> nil
#urprise you see only World! getting printe". hat happene" to the Bello? ell the \r !hara!terstan"s >or !arriage return whi!h eans the Bello "oes get printe". hen the !arriage,!ursor returns
to the beginning o> the line an" orl": gets over written on it. -i&e \r stan"s >or !arriage return \n
stan"s >or newline. ype the e(aple below in irb
>> puts "Hello \n World!"
Hello
World!
=> nil
As you !an see Hello gets printe" in >irst line an" World! gets printe" in ne(t. his is be!ause we
7 A agi!al wor" uttere" by saints in In"ia
29
-
8/18/2019 FSF - I Love Ruby - 2012
24/170
I Love Ruby 2012 Edition
have pla!e" a new line !hara!ter \n in between the.
ell now lets ta&e a s!enario we now &now that \r \n an" possibly others are non printing
!hara!ters. +ow how to print \n or \r in our output. As it turns out that putting a "ouble ba!&war"
slash woul" print a ba!&war" slash in output as "eonstrate" by e(aple below.
>> puts "Hello \\n World! => Hello \n World!"
Hello \n World! => Hello
World!
=> nil
In a siilar >ashion \t puts tab spa!es where ever they are pla!e". ry the e(aple below
>> puts "Tabs \t leave\tlong spaces"
Tabs leave long spaces
=> nil
I hope you have un"erstoo" soething about #trings lets ove on......
Using !ext Editor
ill now you have &eye" in sall progras into your irb when you are "eveloping large so>tware
you !ant e(pe!t the en" user or your !lients to &eep &eying in into the !onsole the stateents you
have "evelope" >or hi , her instea" you will be han"ing over a type" Ruby progra whi!h they
!an run it to a!!oplish !ertain tas&. -ets see how to use a te(t e"itor to write progras.
0arlier in Installing ID0 se!tion I have type" about how to install a siple Integrate" Developent
0nvironent OID0 !alle" %eany. I> you are using *buntu press super &ey type in %eany !li!& on
the %eany i!on an" you will get it.
Gou !an use other ID0s too i> want other ID0 re>er to their "o!uentation >or installation
instru!tions. In the ID0 type the >ollowing progra
24
-
8/18/2019 FSF - I Love Ruby - 2012
25/170
I Love Ruby 2012 Edition
puts "Hello World!"
puts "This time I used text editor"
+ow save the >ile as hello_world.rb in a "ire!tory note that Ruby >iles en"s with .rb O"ot rb
e(tension. -aun!h your terinal , !onsole igrate to the "ire!tory where progra is store" an"
type the >ollowing in it
ruby hello_world.rb
an" heres how you will get the output.
Hello World!
This time I used text editor
on"er>ul: Gou have learne" to progra with a te(t e"itor you are getting pro>essional aye:
(rinting &omet#ing#tu"y the !o"e hello_world.rb we have use" a Ruby !oan" !alle" puts this !oan"s
puts soething to the output in this !ase your terinal win"ow.
puts "Hello World!"
puts "This time I used text editor"
he >irst line prints Hello World! an" the se!on" one prints This time I used a text
editor . hat i> you want to print two things in the very sae line? 3or it *se the print
!oan" lets type a new progra hello_world_1.rb >or it in your te(t e"itor type the >ollowing
!o"e
print "Hello World! "
print "Once again I used a text editor"
his gives the output@
Hello World! Once again I used a text editor
#o you have learne" to print soething:
Getting Input
A progra is ore use>ul when it intera!ts with the user lets write a progra that as&s us our nae
an" says hello to us. ype the >ollowing !o"e OI save" it as say_hello.rb
puts "Hello I am Zigor, a automated Robot that says Hello"
print "Please enter your name:"
name = gets()
puts "Hello #{name}"
+ow run it this is how the output will loo& li&e
25
https://raw.github.com/mindaslab/ilrx/master/hello_world.rbhttps://raw.github.com/mindaslab/ilrx/master/hello_world.rbhttps://raw.github.com/mindaslab/ilrx/master/hello_world.rbhttps://raw.github.com/mindaslab/ilrx/master/say_hello.rbhttps://raw.github.com/mindaslab/ilrx/master/hello_world.rbhttps://raw.github.com/mindaslab/ilrx/master/hello_world.rbhttps://raw.github.com/mindaslab/ilrx/master/say_hello.rb
-
8/18/2019 FSF - I Love Ruby - 2012
26/170
I Love Ruby 2012 Edition
Hello I am Zigor, a automated Robot that says Hello
Please enter your name:Karthik
Hello Karthik
-ets wal&thru the progra
he >irst lineputs "Hello I am Zigor, a automated Robot that says Hello"
Prints that the progra nae is Tigor an" its a autoate" robot that wishes you Bello. hen it
prints a line >ee" hen!e the !ontent thats printe" then on goes to the ne(t line
he the se!on" line
print "Please enter your name:"
prints out “Please enter your name:” note that we have use" print here not puts be!ause we
want to get the users nae right a>ter name: I >eel it will be aw&war" i> we let the type nae in
the ne(t line so to avoi" the line >ee" I a using print instea" o> puts.
hen the user enters nae an" presses enter it is !aught by the gets() >un!tion an" the thing you
type" is store" in the variable !alle" nae be!ause o> this pie!e o> !o"e
name = gets()
+ow all our Tigor nee"s to "o is to wish hello >or whi!h we use this !o"e
puts "Hello #{name}"
+oti!e how we are ebe""ing the variable nae into string by putting it between #{ an" }. he
sae e>>e!t !an be a!hieve" by using !o"e li&e this
puts "Hello "+name
Hut "oesnt the >orer pie!e o> !o"e loo& better? Its all your !hoi!e. Ruby let you "o the sae thing
in any ways. Gou !an !hoose anything that you >eel !o>ortable.
Any way in this topi! the line you ust be loo&ing at is one that has gets() etho" or >un!tion it
waits >or a &eyboar" input when you give an input an" press enter it ta&es your input an" assigns
the value to variable in this !ase the variable is nae.
%omments
Coents are sall pie!es o> notes you !an put into a progra so that you or soe one else when
going through the progra 765$ years >ro now will reeber or !oe to &now what its "oing.
Gou ay be sart to"ay but toorrow you ay not be as sart as you are now your boss or !lient
26
-
8/18/2019 FSF - I Love Ruby - 2012
27/170
I Love Ruby 2012 Edition
who has pai" you will yell upon you at that oent to >i( a priority bug or to up"ate a so>tware.
Gou open your "ot rb >ile an" see this !o"e
puts "Hello I am Zigor, a automated Robot that says Hello"
print "Please enter your name:"name = gets()
puts "Hello #{name}"
Gou ight be able to un"erstan" it now but a>ter 765$ years$? At that tie you ight have
>orgotten Ruby altogether: #o start !oenting. #ee the sae progra comment.rb below how it
loo&s li&e ?
# The client is an idiot
# he wants me to update a software after 7,658 years.
# The hell with him
puts "Hello I am Zigor, a automated Robot that says Hello" # zigor is some
stupid robotprint "Please enter your name:" # Tells the user to enter his name
name = gets() # gets the user name and assigns it to a variable named name
puts "Hello #{name}" # Embeds name into the string that gets printed
-oo& at the !o"e above you have tol" soething about !lient in the >irst three lines. hese lines
start with a # Ohash or !he!& sign. he thing that >ollows a>ter a !he!& sign is a !oent
!oents "ont inter>ere with progras e(e!ution but it !an be use" to provi"e visual hints to
huans o> whats going on in the progra.
+ow lets loo& at this line
puts "Hello #{name}" # Embeds name into the string that gets printed
here you have #{name} en!lose" within "ouble 8uotes hen!es its treate" as a ebe""e" ruby !o"e
in a string rather than a !oent whereas # Embeds name into the string that gets
printed is treate" as !oent.
#o I hope you un"erstan" that !oent !an one "ay help. Pro>essionals always !oent when they
write !o"e. hey will ta&e pains that alost any Ruby !o"er who rea"s their progra will be able to
un"erstan" how it wo&s.
Multiline omments
I> you want to put lot o> !oents about the siFe o> a paragraph then you !an put that pie!e o> te(t
between =begin an" =end as shown in the progra comments_multiline.rb below
=begin The client is an idiot
he wants me to update a software after 7,658 years.
The hell with him
$ Gou !an live so long i> s!ien!e progresses >ast enough. Resear!hes have "ata to a&e you live so long: #o behope>ul.
27
https://raw.github.com/mindaslab/ilrx/master/comment.rbhttps://raw.github.com/mindaslab/ilrx/master/comments_multiline.rbhttps://raw.github.com/mindaslab/ilrx/master/comment.rbhttps://raw.github.com/mindaslab/ilrx/master/comments_multiline.rb
-
8/18/2019 FSF - I Love Ruby - 2012
28/170
I Love Ruby 2012 Edition
=end
puts "Hello I am Zigor, a automated Robot that says Hello" # zigor is some stupid robot
print "Please enter your name:" # Tells the user to enter his name
name = gets() # gets the user name and assigns it to a variable named name
puts "Hello #{name}" # Embeds name into the string that gets printed
In the !o"e above note how we put these te(t@
The client is an idiot
he wants me to update a software after 7,658 years.
The hell with him
between =begin an" =end when you e(e!ute the progra those between the =begin an" =end
will be ignore". #o "ont hesitate to write a lot o> !oent as now you &now there is a way to "o it
an" it will bene>it you an" your >ellow prograers greatly.
2$
-
8/18/2019 FSF - I Love Ruby - 2012
29/170
I Love Ruby 2012 Edition
Comparison and !ogic
Logical 'perators
-ogi!al operators lets you "eterine weather soe thing is true or not. 3or e(aple one is one
thats what huans thin& lets see what !oputers thin& about it. 3ire your irb an" type one e8uals to
one as shown
>> 1 == 1
=> true
ell whats that "ouble e8ual to sign? A single e8ual to sign eans assignent >or e(aple a ; 5
puts value 5 into a. A "ouble e8ual to sign is !oparison. #o above we have !he!&e" i> 1 is e8ual to
1 an" the answer is true. Coputers are intelligent arent they?
K now lets !he!& i> 1 e8uals to 2 so we type 1;;2 an"....
>> 1 == 2
=> false
he !oputer ORuby interpreter in this !ase tells its >alse. ell .. what to say?'
3ine i> 1 is not e8ual to 2 to a !oputer when we type it it ust putout true so type it in your
!onsole
>> 1 != 2
=> true
he :; stan"s >or not e8ual to. he : #tan"s >or not
+ow we !he!& i> one is not e8ual to 1 an" the !oputer as e(pe!te" gives >alse as output.
>> 1 != 1
=> false
e now !he!& i> 2 is greater than 9 >or greater than we use U sign
>> 2 > 3
=> false
h: 2 is not greater than 9 poor poor 2 @O
-ets get ore intelligent here we will !he!& i> 2 is less than 9 >or less than we use V sign
>> 2 < 3
=> true
Cool: e >oun" that i> 2 is not greater than 9 then its less than 9. ell we are going to get a +obel
' Rea" a atheati!al proo> that !oputers "o go wrong
2'
-
8/18/2019 FSF - I Love Ruby - 2012
30/170
I Love Ruby 2012 Edition
priFe >or /ath1).
he U; stan"s >or greater than or e8ual to
>> 5 >= 3
=> true
#in!e 5 is greater than 9 it returns true
#ee the e(pression below it still returns true be!ause 5 is e8ual to 5
>> 5 >= 5
=> true
5 is not greater than 5 so it returns >alse
>> 5 > 5
=> false
9 is less than 5 hen!e the less than or e8ual to operator V; returns true
>> 3 true
9 is e8ual to 9 hen!e the less than or e8ual to operator still returns true
>> 3 true
9 is not less than 9 its e8ual to 9 Osiilar to all huans are e8ual hen!e the less than operator
returns >alse
>> 3 < 3=> false
Gou !an also try these with nubers
perator /eaning
!< +ot less than
!> +ot greater than
t rue 12 3true4
In the logi! operator se!tion you ight see that irb gives true or >alse as output. Gou ustnt !on>use
with ortunately the +obel !oittee tol" e that i> I ha" "is!overe" 2 is less than 9 in $)))) H.C itwoul" awar" e the +obel priFe. #oe !ra!& seee" to have "is!overe" it be>ore I "i". Any way no proble i> I
!an invent a tie a!hine an" goto $)))) HC an" announ!e y great "is!overy I will get the +obel. #o I ight onor o>> writing the boo& as I have to !on!entrate y energy on inventing ie /a!hine.
9)
-
8/18/2019 FSF - I Love Ruby - 2012
31/170
I Love Ruby 2012 Edition
i)
he if &eywor" is use" to e(e!ute a stateent i> a !on"ition is satis>ie". a&e a loo& at the progra
below. 0(e!ute it.# if.rb
puts "Whats your name?"
name = gets.chop
puts "#{name} is genius" if name == "Zigor"
puts "#{name} is idiot" if name != "Zigor"
his is how thee result woul" be i> you give a nae other than Tigor
Whats your name?
Karthik
Karthik is idiot
a&e a loo& at the progra. a&e a loo& at the >ollowing line
puts "#{name} is genius" if name == "Zigor"
he progra gets your nae in variable !alle" name . +ow it !he!&s i> the name is Tigor in the
!o"e highlighte" above i> yes it e(e!utes the stateent asso!iate" with it in this !ase it prints out
that the parti!ular nae is genius. It then !oes "own to ne(t stateent
puts "#{name} is idiot" if name != "Zigor"
In this stateent it !he!&s i> name is not Tigor i> yes it prints the nae is i"iot.
i) else
-ets write the whos genius progra in another >or here we use if else !on"ition instea" o> if .
a&e a loo& at the !o"e below
# Zigor says if the person is intelligent or not
print "Enter your name: "
name = gets.chop
if name == "Zigor"puts "#{name} is intelligent"
elseputs "#{name} is idiot"
end
he progra when e(e!ute" gives the sae output as previous if.rb whats "i>>erent is how the
logi! is represente" insi"e the progra. e see a thing !alle" if name == "Zigor" , then .hat
ha% to be e5ecuted if the code i% true co'e% after that a% %ho.n
if name == "Zigor"
puts "#{name} is intelligent"
+ow we !an put any nuber o> stateents a>ter that if an" all will be e(e!ute" i> the !on"ition
given is satis>ie". 3ine till now but how will Ruby &now where the i> stateent gets over? o say
91
https://raw.github.com/mindaslab/ilrx/master/if.rbhttps://raw.github.com/mindaslab/ilrx/master/if.rbhttps://raw.github.com/mindaslab/ilrx/master/if.rbhttps://raw.github.com/mindaslab/ilrx/master/if.rb
-
8/18/2019 FSF - I Love Ruby - 2012
32/170
I Love Ruby 2012 Edition
that things en" here we put an en" &eywor" as shown.
if name == "Zigor"
puts "#{name} is intelligent"
end
-ets say that that !on"itionOs given in the i> is not satis>ie" an" we nee" to "o soething i>
!on"ition is invali" then we put those stateents that gets e(e!ute" when !on"itions >ails un"er the
else &eywor" as shown
if name == "Zigor"
puts "#{name} is intelligent"
else
puts "#{name} is idiot"end
+ote that the else an" stateents that nee"s to be e(e!ute" when !on"ition >ails !oes be>ore the
end stateent.
elsi)
hen we use if an" else the !o"e un"er if gets e(e!ute" i> the !on"ition is satis>ie" else the
!o"e un"er else se!tion gets e(e!ute". -ets have a new s!enario where the !o"e un"er if is not
satis>ie" then the progra ie"iately Eups to the else se!tion now the logi! "ean"s that we
nee" to !he!& another !on"ition at the else level too what shoul" we "o. o "eal with su!h a
s!enario we !an use the elsif !oan". a&e a loo& at the !o"e below
# elsif.rb
# finds the greatest of three numbers
a,b,c = 3,7,5
if a >= b and a >= c
puts "a = #{a} is greatest"
elsif b >= c and b >= a
puts "b = #{b} is greatest"
else puts "c = #{c} is greatest"
end
hen e(e!ute" it pro"u!es the >ollowing result
b = 7 is greatest
-ets wal&thru the !o"e step by step. -ets loo& at the line
a,b,c = 3,7,5
In this line we assign values 9 7 an" 5 to variables a,b an" c. -ets now !oe to the i> stateent
if a > b and a > c
In this stateent we !he!& i> a is greater than b an" i> a is greater than c. !ote the "e#word and $
he if !on"ition is satis>ie" only i> both !on"itions are true. a is less than b hen!e this !on"ition
92
https://raw.github.com/mindaslab/ilrx/master/elsif.rbhttps://raw.github.com/mindaslab/ilrx/master/elsif.rb
-
8/18/2019 FSF - I Love Ruby - 2012
33/170
I Love Ruby 2012 Edition
>ails so progra s&ips the if stateent an" !oes to the elsif stateent
elsif b > c and b > a
elsif is else plus i> here we !he!& on another two !on"itions thats separate" by an" we !he!& i> b
is greater than a an" i> b is greater than c both are true an" hen!e the stateent un"er elsif
puts "b = #{b} is greatest"
gets e(e!ute" an" we get the result. #in!e the elsif is satis>ie" other else an" the !o"e that !oes
un"er it is ignore".
unless
*nless is another way to !he!& a !on"ition. -et say that one is not a aEor an" is !onsi"ere" a !hil"
unless he or she is less than 1$ years ol". #o how to !o"e it in Ruby? Consi"er the progra below
type it in a te(t e"itor an" e(e!ute it.
# unless.rb
print "Enter your age:"
age = gets.to_i
p "You are a minor" unless age >= 18
hen e(e!ute" this is what we get
Enter your age:16
"You are a minor"
he progra as&s your age it says you are inor i> age is not greater than 1$. hat is it says you
are a inor i> unless your age is greater than or e8ual to 1$ Osee the highlighte" !o"e. he p is a
&in" o> short >or >or puts. I> you write puts “something” the ruby interpreter prints something .
I> you use p ”something” the ruby intreprete prints ”something” .
unless else
Just li&e if with else we !an have else in an unless stateent. ype in the progra below an"
e(e!ute it
# unless_1.rb
print "Enter your age:"
age = gets.to_i
unless age >= 18
p "You are a minor"
else p "You are a grown up"
end
his is what you get when you e(e!ute it
Enter your age:37
"You are a grown up"
99
https://raw.github.com/mindaslab/ilrx/master/unless.rbhttps://raw.github.com/mindaslab/ilrx/master/unless_1.rbhttps://raw.github.com/mindaslab/ilrx/master/unless.rbhttps://raw.github.com/mindaslab/ilrx/master/unless_1.rb
-
8/18/2019 FSF - I Love Ruby - 2012
34/170
I Love Ruby 2012 Edition
K here is how it wor&s you get your age !onvert it into integer an" store it in a variable !alle"
age. Con!entrate on the highlighte" !o"e unless the age is less than 1$ the age is greater than or e8ual to 1$ it gets route" to the else stateent an" or are"
>or!es the person shoul" be between 1$ an" 95 years o> age our progra as&s the "etails >ro a
person who wishes to enroll it !he!&s his age an" tells the result. ype the progra below an"
e(e!ute it
# unless_2.rb
print "Enter your age:"age = gets.to_i
unless age < 18 or age > 35
p "You can enter Armed forces"
else p "You cannot enter Army. You are either too young or too old"
end
hen e(e!ute" this will be the result
Enter your age:23
"You can enter Armed forces"
I thin& you !an e(plain this progra on your own. I> else !onta!t e I will write an e(planation.
case w#en
#uppose you want to write a progra that has a "eterine" output >or "eterine" input you !an
use the !ase when. -ets say that we want to write a progra that spells >ro 1 to 5 we !an "o it as
shown in case_when.rb type the progra in te(t e"itor an" e(e!ute it.
# case_when.rb
# This program spells from one to five
print "Enter a number (1-5):"
a = gets.to_i
spell = String.new
case a
when 1
spell = "one"
when 2
spell = "two"
when 3
spell = "three"
when 4
spell = "four"
when 5
spell = "five"
94
https://raw.github.com/mindaslab/ilrx/master/unless2.rbhttps://raw.github.com/mindaslab/ilrx/master/case_when.rbhttps://raw.github.com/mindaslab/ilrx/master/unless2.rbhttps://raw.github.com/mindaslab/ilrx/master/case_when.rb
-
8/18/2019 FSF - I Love Ruby - 2012
35/170
I Love Ruby 2012 Edition
else
spell = nil
end
puts "The number you entered is "+spell if spell
utput
Enter a number (1-5):4
The number you entered is four
-ets see how the above progra wor&s. 3irst the user is propte" to enter a nuber when he "oes
enters a nuber it gets !onverte" >ro #tring to Integer by the >ollowing stateent
a = gets.to_i
he variable a now !ontains the value o> nuber we have entere" we have the !ase stateent as
shown
case a
…......
end
In the above epty !ase stateent we are going to write !o"e that gets e(e!ute" "epen"ing on the
value o> a. hen a is 1 we nee" to spell out as ollowing !o"e
case a
when 1
spell = "one"end
#iilarly we a"" !o"e till the !ase is 5 as showncase a
when 1
spell = "one"
when 2
spell = "two"
when 3
spell = "three"
when 4
spell = "four"
when 5
spell = "five"end
here !oul" be a !ase when the huan who runs this progra !oul" give a wrong input so we nee"
to "eal with those !ases too >or that we a"" a spe!ial stateent !alle" else i> all the when !ases
>ails the !o"e un"er else is e(e!ute" it ust however be note" that its not an"atory to have an
else between !ase en" blo!&. #o now the progra !hanges as shown
case a
when 1
spell = "one"
when 2
spell = "two"
when 3
95
-
8/18/2019 FSF - I Love Ruby - 2012
36/170
I Love Ruby 2012 Edition
spell = "three"
when 4
spell = "four"
when 5
spell = "five"
else
spell = nilend
+e(t all we ust "o is to print out spell whi!h we "o it in the >ollowing stateents
puts "The number you entered is "+spell if spell
+ote that we print out only i> spell !ontains a value else i> spell is nil nothing is printe". It is ta&en
!are by the i> !on"ition thats been highlighte" above.
#oeties it ight be ne!essary that we nee" to e(e!ute sae set o> stateents >or any
!on"itions. -ets ta&e a saple appli!ation in whi!h the progra "eterines a nuber >ro 1 to 1)Oboth in!lusive an" the progra tells weather the nuber is o"" or even. ype the !o"e below
Ocase_odd_even.rb an" e(e!ute it
# case_odd_even.rb
num = 7 # put any number from 1 to 10
case num
when 1, 3, 5, 7, 9puts "#{num} is odd"
when 2, 4, 6, 8, 10
puts "#{num} is even"end
utput
7 is odd
+oti!e that in above progra we assign a value 7 to a variable num ne(t we put the num in a !ase
stateent. hen the nuber is 1 9 5 7 an" ' we nee" to print its o"" so all we "o is to group the
!ases. hen its satis>ie" it ust print as o"" >or that its Eust enough i> you put it as shown in
highlighte" !o"e below
case numwhen 1, 3, 5, 7, 9
puts "#{num} is odd"end
+e(t all we nee" to print the nuber is even i> its 2 4 6 $ an" 1) to "o this tas& all we nee" to "o
is to a"" !o"e that highlighte" below
case num
when 1, 3, 5, 7, 9
puts "#{num} is odd"
when 2, 4, 6, 8, 10
puts "#{num} is even"
end
96
https://raw.github.com/mindaslab/ilrx/master/case_odd_even.rbhttps://raw.github.com/mindaslab/ilrx/master/case_odd_even.rb
-
8/18/2019 FSF - I Love Ruby - 2012
37/170
I Love Ruby 2012 Edition
hats it. he !o"e will wor& >ine >or all nubers >ro 1 to 1). he oral o> the story is we !an
easily group !ases an" e(e!ute a !oon !o"e un"er it.
* +he ?@ is !alle" tertiary operator. It !an be use" as a siple if . a&e the progra shown below.
Con!entrate on the highlighte" !o"e below
# max_of_nums.rb
a,b = 3,5
max = a > b ? a : bp "max = "+max.to_s
hen e(e!ute" the progra gives the >ollowing output
"max = 5"
ell the ?: wor&s as >ollows. It synta( is li&e this
? :
Gou give an e(pression be>ore the 8uestion ar&. his e(pression ust either return true or >alse. I>
the e(pression returns true it returns the stu>> between ? an" : i> >alse it returns the stu>> a>ter @
In the e(pression
max = a > b ? a : b
e !an substitute the values o> a an" b as >ollows
max = 3 > 5 ? 3 : 5
9 is not greater than 5 hen!e its >alse. Ben!e the value a>ter @ is assigne" to a(. Ben!e a(
be!oes 5.
97
https://raw.github.com/mindaslab/ilrx/master/max_of_nums.rbhttps://raw.github.com/mindaslab/ilrx/master/max_of_nums.rb
-
8/18/2019 FSF - I Love Ruby - 2012
38/170
I Love Ruby 2012 Edition
!oops
At ties you ight nee" to "o soe repetitive tas& lets say that I want to write a ro!&et !ount"own
progra I want to !reate a autoate" robot that !ount "own >or ro!&ets when the !ount is >inishe"
it says >= lets write one an" see
# count_down.rb
# Zigor tells about itself
puts "Hello, I am Zigor...."
puts "I count down for rockets"# Count down starts
puts 10
p 9 # p is a short form for puts
p 8
p 7
p 6
p 5
p 4
p 3
p 2
p 1
p "Blast Off!"
ell I hope you un"erstan" the progra above. here is one thing I woul" li&e to e(plain p is ashort >or o> puts rather than writing puts one !an use p an" get the sae result. he above
progra when run prints the >ollowing
Hello, I am Zigor....
I count down for rockets
10
9
8
7
6
5
43
2
1
"Blast Off!"
#o a per>e!t e(e!ution but we !an a&e this ore e>>i!ient we will soon see how
downto
In your te(t e"itor type the >ollowing progra
# count_down_1.rb
9$
https://raw.github.com/mindaslab/ilrx/master/count_down.rbhttps://raw.github.com/mindaslab/ilrx/master/count_down_1.rbhttps://raw.github.com/mindaslab/ilrx/master/count_down.rbhttps://raw.github.com/mindaslab/ilrx/master/count_down_1.rb
-
8/18/2019 FSF - I Love Ruby - 2012
39/170
I Love Ruby 2012 Edition
# Zigor tells about itself
puts "Hello, I am Zigor...."
puts "I count down for rockets"
# Count down starts
10.downto 1 do |num|
p num
end p "Blast Off!"
Run it an" see. ell your progra uses up a lot less !o"e an" yet it pro"u!es the sae result: o
&now how the progra runs loo& at the !o"e highlighte" noti!e the thing 10.downto 1 this
stateent a&e Tigor !ount "own >ro 1) to 1 while it !ount "owns you !an "o soe thing with
the !ount"own value you !an put soe !o"e in the loop blo!&. he loop starts with a do an" en"s
when it en!ounters a end !oan". Any !o"e you put shoul" be between the do an" end blo!&11 as
shown below
10.downto 1 do
# do some thing! Anything!!
end
#o between the "o an" en" O te!hni!ally its !alle" a blo!& you !an put the !o"e to print the !ount
"own nuber. 3irst how to get the nuber we will get it in a variable !alle" nu so we rewrite the
!o"e as shown
10.downto 1 do |num|
# put the printing stuff here
end
+oti!e above that nu is surroun"e" byW an" W. All we nee" to "o now is to print it so we Eust print
it:
10.downto 1 do |num|
p num
end
times
ties is a very siple loop i> you want to get a !o"e e(e!ute" + nuber o> ties you put the !o"e
in it. +ow lets see what Tigor &nows
# times.rb
puts "Hi, I am Zigor"
puts "I am going to tell what I know"
7.times{
puts "I know something"
}
ell when e(e!ute" the progra prints the >ollowing
11 Gou !an use open an" !lose" >lower , !urly bra!&ets X an" Y instea" o> "o an" en" in Ruby
9'
https://raw.github.com/mindaslab/ilrx/master/times.rbhttps://raw.github.com/mindaslab/ilrx/master/times.rb
-
8/18/2019 FSF - I Love Ruby - 2012
40/170
I Love Ruby 2012 Edition
Hi, I am Zigor
I am going to tell what I know
I know something
I know something
I know something
I know something
I know something
I know something
I know something
Tigor tells that it &nows soething seven ties.
K we have a"e !hanges in the progra we are printing the !ount variable this tie type the
progra below an" e(e!ute
# times_1.rb
puts "Hi, I am Zigor"
puts "I am going to tell what I know"7.times{ |a|
puts "#{a}. I know something"
}
Bere is what you get the result
Hi, I am Zigor
I am going to tell what I know
0. I know something
1. I know something
2. I know something
3. I know something
4. I know something
5. I know something
6. I know something
hy its !ounting >ro Fero to si( rather than one to seven? ell i> all happens as you want there
will be no nee" o> prograers li&e you an" e so "ont bother. +oti!e that in these progras we
use { an" } rather than do an" end . ell Ruby en!ourages "i>>erent styles o> prograing.
upto
upto !ounts soe nuber upto soe other nuber. Its li&e downto in reverse. ype in the progra
below an" e(e!ute it
# upto.rb
# upto is downto in reverse
17.upto 23 do |i|
print "#{i}, "
end
An" here is how the output loo&s li&e
17, 18, 19, 20, 21, 22, 23,
4)
https://raw.github.com/mindaslab/ilrx/master/times_1.rbhttps://raw.github.com/mindaslab/ilrx/master/upto.rbhttps://raw.github.com/mindaslab/ilrx/master/times_1.rbhttps://raw.github.com/mindaslab/ilrx/master/upto.rb
-
8/18/2019 FSF - I Love Ruby - 2012
41/170
I Love Ruby 2012 Edition
step
step loop !an be thought as !obination o> upto an" downto all pa!&e" in one e(e!ute the !o"e
shown below# step _1.rb
# explains step function
1.step 10 do |i|
print "#{i}, "
end
an" here is the result. his is very siilar to upto: Dont you see::
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
+ow lets o"i>y the progra as shown below an" save it in another nae
# step _2.rb
# explains step function
10.step 1 do |i|
print "#{i}, "
end
hen e(e!ute" this progra pro"u!es no output. hat have we "one wrong? /o"i>y the progra
as shown below an" run it
# step_3.rb
# explains step function
# this time its stepping down
10.step 1, -1 do |i|
print "#{i}, "
end
ell here is the output o> the progra
10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
hat goes on in step? step re!eives three inputs !onsi"er the !o"e shown below
10.step 1, -1
he >irst one is the nuber that !alls step is ta&en as the initial nuber in the above !ase it is 1).
+e(t is the en"ing nuber in this !ase it is 1 that is this >un!tion !ounts >ro 1) to 1 we ust
"es!en" in this !ase so the !ount ust be in steps o> 1.
I !an o"i>y the sae progra to print even nubers in 1) to 1 as shown
# step_4.rb
# explains step function
# this time its stepping down
p "Even numbers between 10 and 1:"
10.step 1, -2 do |i|
print "#{i}, "
end
his progra prints the >ollowing output
“Even numbers between 10 and 1:”
41
https://raw.github.com/mindaslab/ilrx/master/step_1.rbhttps://raw.github.com/mindaslab/ilrx/master/step_1.rbhttps://raw.github.com/mindaslab/ilrx/master/step_1.rbhttps://raw.github.com/mindaslab/ilrx/master/step_1.rbhttps://raw.github.com/mindaslab/ilrx/master/step_2.rbhttps://raw.github.com/mindaslab/ilrx/master/step_2.rbhttps://raw.github.com/mindaslab/ilrx/master/step_2.rbhttps://raw.github.com/mindaslab/ilrx/master/step_2.rbhttps://raw.github.com/mindaslab/ilrx/master/step_3.rbhttps://raw.github.com/mindaslab/ilrx/master/step_4.rbhttps://raw.github.com/mindaslab/ilrx/master/step_1.rbhttps://raw.github.com/mindaslab/ilrx/master/step_1.rbhttps://raw.github.com/mindaslab/ilrx/master/step_2.rbhttps://raw.github.com/mindaslab/ilrx/master/step_2.rbhttps://raw.github.com/mindaslab/ilrx/master/step_3.rbhttps://raw.github.com/mindaslab/ilrx/master/step_4.rb
-
8/18/2019 FSF - I Love Ruby - 2012
42/170
I Love Ruby 2012 Edition
10, 8, 6, 4, 2,
-ets now try a progra that will print even nubers >ro 1 to 1) this tie in as!en"ing or"er
# step_5.rb
# explains step function
# this time its stepping upby two counts each loopp "Even numbers between 1 and 10:"
2.step 10, 2 do |i|print "#{i}, "
end
utput
“Even numbers between 1 and 10:”
2, 4, 6, 8, 10,
#ee the highlighte" or "ar&ene" !o"e above. e have starte" >ro 2we will en" at 1) an" we Eup
ea!h loop by steps o> 2. Insi"e the loop we siply print the iterating value whi!h is !apture" in
variable i.
w#ile
hile loop is a loop that "oes soething till a !on"ition is satis>ie". Rea" the !o"e below
# while .rb
i=1
while iollowing output.
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
-ets now see how an while loop wor&s. A while loop norally has >our iportant parts
5. InitialiFation
6. Con"ition !he!&
7. -oop bo"y
$. *p"ation
InitialiFation
#ee the stateent i=1 here we initialiFe a variable nae" i an" set it to value 1.
Con"ition !he!&
#ee the stateent while iy that we are starting a while loop this
42
https://raw.github.com/mindaslab/ilrx/master/step_5.rbhttps://raw.github.com/mindaslab/ilrx/master/while.rbhttps://raw.github.com/mindaslab/ilrx/master/while.rbhttps://raw.github.com/mindaslab/ilrx/master/while.rbhttps://raw.github.com/mindaslab/ilrx/master/step_5.rbhttps://raw.github.com/mindaslab/ilrx/master/while.rbhttps://raw.github.com/mindaslab/ilrx/master/while.rb
-
8/18/2019 FSF - I Love Ruby - 2012
43/170
I Love Ruby 2012 Edition
while loop on every iteration !he!&s the value o> ii> its less than or e8ual to 1) the loops bo"y
gets blin"ly e(e!ute"
-oop bo"y
+oti!e the do an" end in the progra. hey en!apsulate a pie!e o> !o"e. he do syboliFes the
start o> loop !o"e blo!& the end syboliFes the en" o> loop !o"e blo!&. Hetween it we have soe
stateents about whi!h we will "is!uss soon. ne o> the stateent is to print the value o> i whi!h
is a!!oplishe" by print "#{i}, "
*p"ation
-ets say that we >orgot to in!lu"e i+=1 in the loop bo"y at the en" o> ea!h iteration the value o> iwill always reain 1 an" i will always reain less than 1) hen!e the loop will be e(e!ute" in>inite
nuber o> ties an" will print in>inite 1s, . In pra!ti!al ters your progra will !rash with possible
un"esirable !onse8uen!e. o avoi" this we ust in!lu"e a up"ation stateent. Bere we have put
i+=1 whi!h in!reents i by value one every tie an iteration !ontinues this ensures that ialse at soe stage an" hen!e the loops stops e(e!ution12.
Ben!e we see that >or a loop to wor& in an "esirable anner we nee" to get these >our parts into
syphony.
until
While loop &eeps going until a !on"ition be!oes >alse until loop &eeps going until a
!on"ition be!oes true. Rea" the !o"e below type it in a te(t e"itor an" e(e!ute it.
# until .rb
i=1
until i>10 do
print "#{i}, "i+=1
end
his is what you will get as result
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
#o how this loop wor&s? At >irst we "o set i=1 then we use the until !oan" an" say that until i
is greater than 1) &eep "oing soe thing Oloo& at the highlighte" !o"e. hat shoul" be "one is sai"
between the do an" end &ey wor"s. #o till the !on"ition >ails the !o"e in loops bo"y will be
12 #oe !ases a loop ight be let to run in>inite ties Otheoreti!ally. Currently those things are outsi"e the s!ope o>this boo&.
49
https://raw.github.com/mindaslab/ilrx/master/until.rbhttps://raw.github.com/mindaslab/ilrx/master/until.rbhttps://raw.github.com/mindaslab/ilrx/master/until.rbhttps://raw.github.com/mindaslab/ilrx/master/until.rbhttps://raw.github.com/mindaslab/ilrx/master/until.rb
-
8/18/2019 FSF - I Love Ruby - 2012
44/170
I Love Ruby 2012 Edition
e(e!ute" so we get 1 to 1) printe" as output.
brea,
#uppose you want to brea& away >ro loop you !an use the break !oan". An e(aple is given
below. In the e(aple we will brea& i> the iterating variable i be!oes 6. #o nubers ranging only
>ro 1 to 5 gets printe". hen i be!oes 6 the loop brea&s or terinates
#break.rb
1.upto 10 do |i|
break if i == 6print "#{i}, "
end
hen e(e!ute" the above progra pro"u!es the >ollowing output
1, 2, 3, 4, 5,
44
https://raw.github.com/mindaslab/ilrx/master/break.rbhttps://raw.github.com/mindaslab/ilrx/master/break.rb
-
8/18/2019 FSF - I Love Ruby - 2012
45/170
I Love Ruby 2012 Edition
"rrays
Arrays !an be !onsi"ere" as ra!& you !an &eep any thing19 in a ra!& in a siilar way you !an &eep
any thing in an array. A ra!& !ontains any shel>s or !opartents. I> you !an !ount the you !an
put nubers on ea!h !opartent the ra!& !an be !onsi"ere" an array o> spa!e to store soe thing.
0a!h !opartent !an be i"enti>ie" by a nuber an" hen!e it be!oes easy to i"enti>y it. An array
is a ra!& thats available to a prograer. -ets see an e(aple to learn ore. ype the progra
below an" e(e!ute it
# array.rb
my_array = []
my_array irst stateent we appen" a string !onstant “Something” in
the se!on" stateent we appen" a integer 123 an" in the thir" stateent we appen" the !urrent tie.
I> you have guesse" it right we have use"
-
8/18/2019 FSF - I Love Ruby - 2012
46/170
I Love Ruby 2012 Edition
K we have to "o soe thing with ea!h eleent o> an array. o "o so we a"" a do … end within
it we !an "o soething so our !o"e gets trans>ore" as
my_array.each do
ende have to !apture ea!h eleent o> an array into a variable lets use a variable nae" element to
"o the Eob so we !apture ea!h eleent using the >ollowing !o"e
my_array.each do |element|
end
+oti!e that how we put our eleent variable between | an" |. e have !apture" ea!h an" every
eleent o> an array what to "o? we will print it using a puts stateent. #o our array gets printe"
su!!ess>ully. he >ollowing progra too wor&s the sae way as previous progra but we use
Array.new instea" o> [] to say that my_array is an array
# array_1.rb
my_array = Array.newmy_array
-
8/18/2019 FSF - I Love Ruby - 2012
47/170
I Love Ruby 2012 Edition
another way o> "e!laring array. #o the progra array_3.rb wor&s e(a!tly sae as array_1.rb an"
array.rb% but its ore !on!ise. *nli&e any languages Ruby lets the prograer !hoose his own
style o> !o"ing.
# array_3.rb
my_array = [ "Something", 123, Time.now ]puts my_array.join("\n")
Result
Something
123
Wed Feb 03 17:37:36 +0530 2010
More on -rray -ets now see soe array >un!tions. 3or this we will be using our >avorite irb rather than a te(t e"itor
>> array = Array.new
=> []
K in the above stateent we see that we !reate an Array nae" array using Array.new . Array.new
!reates an epty array.
here is another way to !reate an array. e !an !reate it by "ire!tly spe!i>ying the values that are
!ontaine" in an array as shown
>> array = ["Something", 123, Time.now]
=> ["Something", 123, Tue Feb 02 20:30:41 +0530 2010]
In the above stateent we !reate an array with three obEe!ts in it. he value that ust be in an array
is given between s8uare bra!&ets Z an" [. 0a!h obEe!t in array is separate" by a !oa. Hy
provi"ing no values between Z an" [ we !an even !reate an epty array as shown
>> array = []
=> []
In the above e(aple the epty Z[ "oes the sae Eob as Array.new .
-ets !reate array with paraeters with Array.new as shown
>> array = Array.new("Something", 123, Time.now)
ArgumentError: wrong number of arguments (3 for 2)
from (irb):3:in `initialize'
from (irb):3:in `new'
from (irb):3
from :0
As you see above it >ails: Dont use it that way.
K lets now try soe thing on the array >irst to get how any eleents are in the array we !an use
47
https://raw.github.com/mindaslab/ilrx/master/array_3.rbhttps://raw.github.com/mindaslab/ilrx/master/array_3.rb
-
8/18/2019 FSF - I Love Ruby - 2012
48/170
I Love Ruby 2012 Edition
the length >un!tion as shown below@
>> array.length
=> 3
he Eoin >un!tion Eoins any array eleents together an" returns it. #o when our array eleent is
Eoine" this is what we get as result@
>> array.join(', ')
=> "Something, 123, Tue Feb 02 20:30:41 +0530 2010"
+ote that we pass a string to the Eoin when the array eleents are Eoine" as a string the string we
passe" gets inserte" into the in between.
e have !reate" an array an" we have soething in it what i> we want to a"" soething to it? o
"o so we use the push etho". In the e(aple below we push a nuber 5 into the array an" as we
see the array gets e(pan"e" an" 5 is appen"e" to the array at the last.
>> array.push(5)
=> ["Something", 123, Tue Feb 02 20:30:41 +0530 2010, 5]
he pop etho" "oes the opposite o> push it pops out or reoves the last eleent o> array. #ee the
e(aple below we pop an eleent an" the last eleent whi!h is 5 gets poppe" out.
>> array.pop
=> 5
A>ter popping it out lets see whats in the array
>> array
=> ["Something", 123, Tue Feb 02 20:30:41 +0530 2010]
e see that the array siFe has re"u!e" by one an" last eleent 5 is issing.
Its not that you ust only give a >i(e" values in push you !an give variables an" Ruby e(pressions
an" any obEe!t to the push as arguent. Gou !an see below that we are pushing 2 raise" to the
power o> 1) to the array an" 1)24 gets a""e" to the array at the last.
>> array.push 2**10
=> ["Something", 123, Tue Feb 02 20:30:41 +0530 2010, 1024]
Array eleents are in"e(e". he >irst eleent o> an array has a in"e( nuber ) an" its goes on
Otheoreti!ally till in>inity. I> one wants to a!!ess eleent at in"e( n14 all he nee"s to "o is to put
the in"e( nuber in between s8uare bra!&ets. In the e(aple below we a!!ess the thir" eleent in
the array nae" array so we type it as >ollows
>> array[2]
=> Tue Feb 02 20:30:41 +0530 2010
he pop etho" too a!!epts a 3i(nu15 as an arguent whi!h it uses to pop all eleents starting
14 n is a nuber15 A nuber
4$
-
8/18/2019 FSF - I Love Ruby - 2012
49/170
I Love Ruby 2012 Edition
>ro that in"e( an" >urther.
>> array.pop(2)
=> [Tue Feb 02 20:30:41 +0530 2010, 1024]
>> array
=> ["Something", 123]
As you see the thir" eleent gets poppe" out so popping at ran"o is possible.
e !an push any eleents into an array at on!e. Consi"er the !o"e snippet below
>> array.push 5, "Who am I?", 23.465*24
=> ["Something", 123, 5, "Who am I?", 563.16]
e >irst push 9 new eleents into the array an" so we get a bigger one.
+ow we pop all eleents whos in"e( nuber is 9 an" above by giving array.pop 3
>> array.pop 3=> [5, "Who am I?", 563.16]
As you !an see the array siFe is re"u!e" an" it now only has two eleents.
>> array
=> ["Something", 123]
here is another way to appen" eleents in an array its by using the "ouble less than operator VV
let push soe eleents into the array with it as shown@
>> array ["Something", 123, "a new element"]
>> array ["Something", 123, "a new element", 64]
as you see above we have appen"e" a #tring !onstant “a new element” an" 64 to the array using
orgotten about it. Gou !an treat array as set an" "o any
operations on it. Bere are a >ew e(aples whi!h I trie" out on irb
4'
-
8/18/2019 FSF - I Love Ruby - 2012
50/170
I Love Ruby 2012 Edition
-ets ta&e a !ollege volleyball tea in it are soe people naes Asho& Chavan Karthi& Jesus an"
Hu"ha. I> you ta&e a list o> !ri!&et tea there are Hu"ha Karthi& Ragu an" Ra. -ets now !o"e it
in ruby. o have a !olle!tion o> people who play in volleyball tea we !reate an array as shown
>> volleyball=["Ashok", "Chavan", "Karthik", "Jesus", "Budha"]
=> ["Ashok", "Chavan", "Karthik", "Jesus", "Budha"]
In a siilar way we !reate another array that !ontains naes o> those who play in !ri!&et tea as
shown
>> cricket=["Budha", "Karthik", "Ragu", "Ram"]
=> ["Budha", "Karthik", "Ragu", "Ram"]
#o we have two sets o> people. +ow to >in" out who are in volley ball an" !ri!&et all we nee" to "o
is to A+D Oor ta&e interse!tion o> both arrays using the & operator as shown
>> volleyball & cricket=> ["Karthik", "Budha"]
As you see >ro above !o"e snippet the & Oan" operator sni>>s out those eleents that are there in
both arrays. In atheati!s this stu>> is !alle" interse!tion.
-ets say in another situation we woul" li&e to >in" out all those who are both in volleyball an"
!ri!&et tea. o "o so we use the or operator W . -ets now apply it
>> volleyball | cricket
=> ["Ashok", "Chavan", "Karthik", "Jesus", "Budha", "Ragu", "Ram"]
As you see we get naes o> those who are in volleyball an" !ri!&et tea. he W Oor operator is
"i>>erent >ro the Oplus operator. -ets a"" volleyball an" !ri!&et teas
>> volleyball + cricket
=> ["Ashok", "Chavan", "Karthik", "Jesus", "Budha", "Budha", "Karthik", "Ragu",
"Ram"]
As you !an see >ro above !o"e snippet the naes Karthi& an" Hu"ha are "upli!ate". his "oes not
happen when we use the W OR operator.
-ets now >in" that whi!h players play only >or the volleyball tea. 3or this we will inus the
players o> !ri!&et >ro the volleyball tea using the Oinus operator as shown
>> volleyball - cricket
=> ["Ashok", "Chavan", "Jesus"]
#o we see three players are e(!lusively in volleyball tea. #o i> you are a atheati!ian you will
>eel soe what !o>ortable with Ruby.
5)
-
8/18/2019 FSF - I Love Ruby - 2012
51/170
I Love Ruby 2012 Edition
#ashes and Symbols
Bashes are arrays with in"e( "e>ine" by the progra or user an" not by the Ruby interpreter. -ets
see a progra to
top related