Press "Enter" to skip to content

Ruby Programming


well hello internet and welcome to my
Ruby programming tutorial in this one
tutorial I’m going to cover pretty much
95% of the Ruby programming language all
of the basic syntax and Ruby is
basically a dynamic interpreted
object-oriented language in which
everything is an object and all of those
objects can be overwritten Ruby is one
of the easiest languages to read and
learn and with rails it just might be
the best web development option period
in the description underneath this video
you will find easy links to all the
individual pieces of the Ruby
programming language that I cover as
well as a link to all of the code that
is heavily commented and easily
transcribed well enough talking let’s
start writing some code okay on the left
side of the screen I have a basic text
editor which is called sublime text I’m
trying a different color option here so
if you guys liked it please tell me in
the comments section below and on the
right side of the screen I have the
terminal or command line if you were on
Windows and if you want to install Ruby
I’m not going to go through that it’s
very easy just go to Ruby – lang org and
then whatever and installation and here
you’ll find all the information you need
as well as easy installers depending
upon what operating system you’re using
all right so in this first part I’m just
going to briefly cover a whole bunch of
different things
Wow if you want to put a comment in just
put a hash symbol and that is a comment
and I go over other different comments
as well as we continue you want to print
something to the screen very easy to do
you could say something like enter a
value like that and then variables are
either going to start with lowercase
letters or an underscore normally
lowercase letters and of course after
the underscore or lowercase letters
you’re then going to be allowed to use
numbers in your variable names let’s say
I just go and create the normal way of
creating variables is to use dashes
between or underscores between all the
different words in your variable names
and if I want to get data from the user
I just type in gets and then if I want
to convert that from a string to an
integer I would just put dot t– o–
underscore i like then ask them for
another value enter another value and
then get that one as well using gits
once again and it’s very important to
convert
to an integer then another way we can
output data is using puts and the
difference between print and puts is
print will not put a new line after it
prints out your string that on the
screen while puts will puts a new line
and let’s say that we wanted to say
something like first number we want to
convert this back to a string to do so
just put two underscore s if you want to
concatenate or combine strings you just
put the plus sign and I could put
something like plus like this and then
continue on with second number two
underscore s plus equal two and you can
see I’m just continuing to add these
together you can skip over to the next
line and of course you do not need to
put a semicolon at the end of every
statement and then if I wanted to
actually perform some arithmetic inside
of here I can do so and then I would
just convert that to a string and if we
come over here and you can see the name
of my file is Ruby or not Ruby and I’m
just going to type in Ruby to execute it
followed by the RB extension which is
the extension for all Ruby files if I
execute it you can see enter a value I
can type in two and another value three
and there you can see the answer pops up
on the screen now there are five main
rithmetic operators and we of course
have addition subtraction multiplication
division and modulus which returns the
remainder of a division see over here if
I enter those in you can see the answers
that show up there on the screen now
integers or fixed numbers can store
extremely large numbers that do not have
decimal places and you can pretty much
trust an integer can hold well beyond
the number that I displayed here on the
screen so they are quite large and Ruby
uses a different way of storing integers
that allows you to basically be able to
store numbers that are that large now
let’s say I come in here and let’s
create another integer just to show you
an example of the accuracy of floats and
this is a float let’s just say it’s one
point zero zero zero and then let’s
store another float inside of here and
one thing to remember about floats is
there must always be a number before the
decimal place whenever you define them
and then we could come in here and just
go num1 and convert that to a string
plus here let’s do some subtraction this
time no I’m 99 again convert it into a
string plus I’m 1 minus num 99 string
say
if we execute it you can see that it is
quite accurate up until it gets to the
very very end of this float where it has
that nine basically with floats you can
trust that 14 digital accuracy is a
basic norm so let’s come in here and
create a big float and there you go and
then let’s perform a little bit of
arithmetic here big float plus remember
always put the zero there and you can
see that while it will be able to store
up to fourteen digits of accuracy if we
try to perform a calculation like this
that it is not so accurate in performing
that calculation so just like every
other programming language float
arithmetic is a little bit off so you
should be aware of that
now I said before that every single
thing inside of Ruby is an object and
let’s just prove that if we come in here
and type in one dot class which is going
to return the class of whatever precedes
it we could even put a float inside here
dot class and of course we could come in
and put a string inside of here dot
class and what if we execute that you’re
going to see that this comes back to fix
number float and string will get more
examples of exactly what a object is
inside of Ruby basically everything now
a constants going to start with an
uppercase letter so we can put something
like a constant like that and 3.14
however you have to be aware that while
we will say this is a constant that
doesn’t mean we can’t come in and also
change the value what’s going to happen
though whenever we run this and we try
to change the value for the constant
we’re going to get an error but it still
will allow us to change it anyway as you
can see right there there is your
warning da-da-da-da-da
however the constant value did indeed
change and then just to show you one
more advanced thing let’s say that we
want to return a file object it’s quite
easy to do go write handler and we would
use the file object I’ll do a more
advanced tutorial on this later on at
the end of this tutorial but let’s say
we have a file called your sum we want
to write two and we’ll just give this
the out extension and then say that we
want to write to it that’s going to
create the file by the way if it doesn’t
already exist we could then very easily
come in and put some text into that file
let’s say we wanted to put random text
and you could put variables you can put
pretty much anything you want inside of
there but you do need to convert it into
a string we would then
in here and close the file after we are
done with it and then if we wanted to
read data from the file data from file
its equal to we would just use the file
object again and say read and then say
what you wanted to read from say it’s
called your some thought out and then
put the data on the screen we could do
that just that easily and as you can see
data from file is random text just that
easily we’re creating a file wrote to it
closed it reopened it read from it now
putted the data on the screen and then
finally if you wanted to also come in
here and load an execute code another
Ruby file let’s say we have one called
Ruby or not
Ruby dot RB and let’s say give that to
as a value we could then come over here
and create Ruby or not Ruby – and just
say hello from Ruby or not Ruby – save
that and then jump back over here and
there that is file save and execute and
you can see that that is how easy it is
to execute code from other different
files now let’s get into performing some
conditional operations another thing to
remember though first off is if you want
to have a multi-line comment all you
would do is equal begin multi-line
comments and then equals end that is a
weird way of doing a multi-line comment
but that is how they are created in Ruby
now let’s get into conditional
operations let’s say we have a variable
called age and let’s give it the value
of 12 we could come in here now and use
if statements to compare values so we
could say something like if age is
greater than or equal to five we can
also use logical operators like and or
or not and then we go age is less than
or equal to six we could then come in
here don’t need the curly braces you
might be used to say something like
you’re in kindergarten like that we
could then come in and go else if age is
greater than or equal to seven and age
is less than or equal to thirteen and
I’ll put some different data you are in
middle school something else that’s
important is we’re going to be able to
put multiples different statements in
here so we could say yay and then we
could say something like else puts stay
home it’s very important to end your if
statement we
the term end or the key word end if we
execute that you’re in middle school
yeah shows up here on our screen now
it’s very important to know there are a
couple different comparison operators so
the kids Paras and operators are going
to be equal to not equal to less than
greater than less than or equal to as
well as greater than or equal to and
then your logical operators which you’re
going to be able to use to combine and
differentiate those different
comparisons is going to include and or
and not and you could also type and or
or not inside of there if you decided
that would be something you’d rather do
and just to give you a demonstration of
those let’s say we have true and false
is equal to plus true and false to
string and let’s do the same thing for
your other logical operators so here is
or and or and then not let’s just say
not like that and not like that which is
going to return the opposite and there
you can see exactly how those logical
operators are work another comparison
operator you have available to you say
we’d go puts and we wanted to do a
comparison it’s going to provide
different answers depending upon how the
logic works out for that comparison we
have this little guy right here and
basically what it’s going to do is it’s
going to return 0 if both of those
values are equal 1 if the first is
greater and negative 1 if the first is
less than the other one if we want to
perform this operation just to see how
this works out then to string and there
you can see it shot back negative 1 and
the reason why is the first is less than
the other one just going to give you a
rundown of all the different ways to
compare just for completion reasons
unless is another comparison operator
and it just shows unless age is greater
than 4 puts you could say no school else
let’s go to school and then once again
you would put end and you can see go to
school comes up here and the reason why
is this is only going to execute this
line right here if age is less than 4 so
that’s how in less works there’s a bunch
of different ways to do comparisons
inside of Ruby you’re also going to be
able to come in here
and add conditions to the output so we
could say you are young is going to
execute if age is less than 30 and you
can see that it did another way of
comparing things is using the case
statement so we can say something like
print enter greeting go and get that
greeting from the user equal to gets and
then we could put Chomp on the end of
here if we wanted to remove the newline
that goes with the input because the
person types the input and it hits
newline or enter and that’s what Chomp
does gets rid of that newline we could
then create a case statement that says
greeting and then say when what they
type in is equal to French we could also
come in here and put multiple different
stipulations so they can use lowercase
or uppercase well then we’re going to
say Bonjour
once again when they type in Spanish or
lowercase Spanish you could say hola
like that and make sure that is exit and
not end exit there you go and then
finally we could type in else and this
would substitute as the default and
we’ll just put English inside of here
and then we could put puts hello and
then the end is actually the ending for
the case execute and we could just say
nothing and it’s going to say hello and
we could have come in here and say
Spanish it’s going to go jolla and we
could also come in here and get the
English and remove that all together and
you’re going to get exactly the same
results Spanish there you go another
conditional we can use is what is called
the ternary operator and basically it is
going to provide different input
depending upon and conditions so we
could say if the age is greater than or
equal to 50 for example and then we put
a question mark it is going to return
old as the output or the assignment if
the condition is true otherwise it’s
going to return young if the condition
is false and there you can see young
shows up let’s get into looping this
first loop we’re going to demonstrate
we’re going to create a variable give it
a value of 1 and then we’re just going
to type in loop do we could then come in
here and go
x+ or equal to one which is going to be
the shortcut for X is equal to X plus
one same exact thing both of these guys
right here and you can also put comments
right there in the same statement of
course and let’s say that we wanted to
come in here and only print out on the
screen even numbers we could then type
in next unless X modulus 2 is equal to 0
and next what it’s going to do is jump
back here to the top of the loop and
continue iterating through the loop
otherwise if we do have an even number
let’s print that out on the screen and
then let’s also use break which is going
to throw us completely out of the loop
if X is greater than or equal to 10 and
that’s going to stop our looping and
with the loop you’re going to also type
in end you’re going to do that a lot of
times if we execute that you’re going to
see it prints out 2 4 6 8 and 10 so next
if it gets down here it’s going to add a
value of 1 to this which is going to be
2 and in that situation since 2 is an
even number it’s going to print it out
on the screen and then it’s going to
continue it’s going to check is it
greater than or equal to 10 no it’s
going to jump back to the top of the
loop it’s again going to add 1 this time
we’re going to have 3 it’s going to say
does this equal 0
well the modulus of 3 + 2 is going to
kick back 1 so it’s going to say that
that indeed is true so it’s going to
execute next which is going to jump back
up to the loop again it’s going to add 1
to it and you’re going to get a 4 and
continue onward and onwards and then
break of course like I said before
whenever this condition is met and comes
back with a true it’s going to continue
execution after the loop and end the
loop all together let’s go in here and
create ourselves another variable to
show you exactly how it while loops work
inside of Ruby let’s give this value of
1 we could then come in and go while Y
is less than or equal to 10 and then we
could increment the value of Y by 1 we
could then do exactly the same thing
we’ll say next unless Y modulus 2 is
equal to 0 print out on our screen again
the value of y if it’s an even number
and we could also put break inside of
here and say if Y is greater than or
equal to 10 we can kick ourselves out
but the wild loops going to kick us out
anyway because that’s already there so
we can get rid of this all together and
of course we’re going to
while loop with end as well if we
execute that you’re going to see 2 4 6 8
and 10 print I on the screen again told
you there was a bunch of different ways
to loop and use conditionals inside of
here let’s come up and let’s create
another variable and this time we’re
going to cover the until loop which is
just a different way of doing things
basically it’s going to do stuff until a
condition is met
versus end when a condition is met like
the while loop works and to use it you
just go until a is greater than or equal
to 10 and then we’re going to increment
the value of a is equal to 1 and we’re
going to come in here then we could also
put next inside of here if we’d like so
that we can print our awed and even
numbers to is equal to 0 and then in
that situation we could print out on the
screen
the value and again until ends whenever
end is typed in or reached in execution
there you can see is another way to
print out even numbers between 2 and 10
it’s actually a couple different ways to
use for loops all these are sort of
considered for loops we could create
here and array and I’ll get more into
arrays later on it’s just basically a
box that contains a bunch of different
values in memory so there’s numbers we
can come in and go for number in numbers
and in this situation it’s going to be
cycling through this numbers array and
each one of them as we cycle through is
temporarily going to be stored in a
variable called number look at that now
put them by going puts and if you want
to have the value of a variable show up
inside of a string you put the hash
symbol right like that and we go number
like this we could also throw a comm
inside of there in a space if we’d like
and this also ends with end and there
you can see it cycles through all those
and puts commas there on the screen
we could also come in here and go print
like this and that time you can see that
there is no newline we could also come
in here and define an array called
groceries just to show that you can
cycle through pretty much anything let’s
say we have bananas sweet potatoes pasta
and tomatoes there you go that’s our
groceries array we could cycle through
all of these by going groceries each do
you put or food food in this situation
is going to be the temporary holding
cell for each item inside of our
groceries array has its cycles through
these there you go puts get some and
then if we want to
and put the value for food inside of
there there we go
and of course end this with end as well
a whole bunch of different ways that
iterating get some bananas sweet
potatoes pasta and tomatoes I don’t
prints out we could also cycle through
numbers and this is very simple let’s
just say we want to cycle through the
number 0 through 5 this is called a
range which we’ll cover more later on
and then we can go each do again or is
going to be the temporary value as we’re
cycling through then we go puts hash
symbol and then we could put I inside of
here and let’s put another hash symbol
here but this is going to actually be a
hash and there that is and again that’s
going to end with and execute and there
you can see all those printed out so
there’s pretty much every way we can
both use conditionals as well as looping
now let’s take a look at functions now
functions are going to start off with de
F and then you’re going to have your
function name so it’s a add nums then
you’re going to have parameters if any
inside of here so we’ll say num1 and
num2 and then you can either return a
value or not return a value so I’m going
to say num1 and i’m going to convert
this into an integer and then num2 and
convert that into an integer and then
it’s going to return that value and
functions also end with end we could
then come in and go puts add nums and
pass three and four into there and
execute that you can see seven shows up
on the screen now it’s very important to
understand when you’re dealing with
functions the variables are passed by
value so their value can’t be changed
inside of a function so that’s true even
if you have the same name so let’s have
X is equal to one and then we’ll create
a function and change that and we will
pass supposedly X inside of it then
we’ll go and give X the value of four
inside of the function we will then call
change X and we will pass X but this is
this X here we’re passing doesn’t have
anything to do with that and you’re
going to see here if we go puts X is
equal to dot and then we’ll put the hash
some one side of here and X
and execute it it’s going to print out
one so any value that changes inside of
a function is not going to affect an
outside value and this is very important
to remember whenever you’re working with
functions
I’ll get more in functions later on but
that’s the basic gist of how they work
so now let’s take a look at exceptions
now exceptions inside of Ruby a go by
different names we’re going to be able
to catch exceptions in Ruby using both
begin and rescue so we’re going to say
print enter a number and once again
we’re going to get that value and store
it in a variable called first num and
we’ll use gifts and then convert it from
a string into an integer and we’ll then
say that we want to enter another number
and we’ll store this in a variable
called second num and we’ll use gets
again now if we think we might have an
error we’re going to put again and then
we’re going to put some code inside of
here that might throw an error so we’re
going to say answer is equal to first
num / 2nd num then after that we’re
going to type in rescue which is going
to be called if there’s an error and
here we’re expecting the error to be a
division by zero so we’re going to say
you can’t divide by zero and then we’ll
put an end which is actually going to
end the begin and also we could come in
here and throw exit now if we would come
in and go puts first num / 2nd num is
equal to and put answer inside of here
and make sure you put a closing brace
right there as well and execute it let’s
split three inside here and then put
zero and you’re going to see you can’t
divide by zero shows up however if we
would go and do something logical like 4
+ 2 + 3 whatever it doesn’t matter you
can see that it does indeed work you can
also throw your own exceptions with rays
so let’s just come in here and delete
all this and create a function called
check age and pass age inside of here
and give a value of equal to 12 we could
then say raise argument error and we
could say enter a positive number is
going to show up unless age is greater
than 0 we’re going to end that function
right there and then we’re going to also
catch this potential error with rescue
so we could say B
again and then we go check age and let’s
pass negative one inside of there let’s
just ignore the age part there and then
we’ll be able to come in here let’s
indent that and say that we specifically
want to catch an argument error and if
it is triggered we’re going to print out
that is an impossible age and then and
that and you can see if it executes that
is an impossible age prints out there’s
a whole bunch of different ways to use
exceptions inside of Ruby we’ve been
doing a lot of things with strings here
but let’s look specifically at some
string functions and a whole bunch of
other different things basically strings
are just a series of characters either
between double quotes or single quotes
for the most part you’re going to use
double quotes though so let’s just come
in here and go puts add them and one
thing it’s important that I uncover is
if we put a hash symbol in here we’ll
also be able to do things like perform
addition inside of here a whole bunch of
other different things not just variable
names and then we could throw some back
slashes inside of here and let’s look at
the difference between if we would use
double quotes versus single quotes here
we can tell them put a single quote
there and a single quote there execute
that and you’re going to see here that
the new lines indeed do work whenever
you use double quotes as well as this
interpolation which is right here that’s
what that’s called if you want to know
the technical term and whenever you use
single quotes those do not work so
something that’s important to remember
and another reason why we barely ever
use single quotes with strings a here
doc is normally used whenever you want
to use a multi-line string and you want
to continue using all of the new lines
and things so let’s just say multi-line
string and how this would be created as
you’d put these two carrot symbols here
GOM and then you could go something like
this
is a very long string that contains
interpolation like and then you put a
hash symbol inside of there and say
something like four plus five just to do
that and then put some new lines inside
of here just to prove that the new lines
work and then you would end this
multi-line string with the eom at the
end you could then come in
and print that out multi-line string and
execute in there it is you can see all
of those different lines and how they
kept the new lines and everything all in
order with that multi-line string let’s
go and create a couple different strings
here we can say first name is equal to
Derrick and last name is equal to anise
you can combine or concatenate strings
by using a plus sign so we could go a
full name is equal to and first name
plus last name I could go in here and
create another one say middle name is
equal to just and you could also combine
strings with interpolation so we could
say full name is equal to hash symbol
and first name and middle name and then
last name there we are
we could also come in here and check if
a string contains a string and let’s
just use puts here and we go full name
and then we would say include with a
question mark and what you’re looking
for inside of that string maybe we got a
little bit of an error let’s just throw
new and underscore inside of there there
we are there you can see true came back
for that function and we could also get
the number of characters that are inside
of that string there’s 18 to all kinds
of things let’s say that we wanted to
count the number of vowels inside of
here so just go Vale’s and then go full
name dot count and everything you put
inside of here is going to count where
it’s going to find all of them so a e I
owe you and let’s convert that to a
string we could also do the same thing
to find all the consonants so throw that
there consonants and if we’re going to
find the opposite of what we’re
searching for so anything except what we
have listed here we’re just going to put
in a caret symbol like that we could
check that a string starts with another
string puts whole name start with and
then we could throw in last name we
could also come in and get the index
inside of here or the character number
inside of here for a match so we’ll go
full name again and index and then what
we’re searching for specifically worked
out to a string and there you can see
all those print it out for us there’s a
ton of different functions inside of
here
we could also come in and check for
equality let’s go and just delete this
puts so if we want to check a equal to a
then we can go a equal to a you can see
that comes back is true we could also
perform a check to see if something is
the exactly the same object so it puts
if we want it to use a double quote
inside of here we’d have to back slash
that double quote like that then we
could put a and then let’s back clash
the double quote that allows it to be
contained inside a double quotes and
then equal question mark back slash
double quote a back slash double quote
let’s concatenate that and then let’s
actually do operation so we’ll go a and
then equal a again and to string and
there you can see that they show up is
false however if we went in and typed in
puts and say first name dot equal and
then first name inside of there in that
situations going back with a value of
true because they are the same exact
object we could also uppercase every
single thing so just type in uppercase
we could lowercase everything and then
there’s also swap case you can see
exactly what those do there you go let’s
say that we then went into our full name
and we just put in a whole bunch of
spaces inside of here for no good reason
except that we want to show exactly how
to eliminate that whitespace so full
name again we could then strip off all
the left whitespace by going full name
equal to full name dot L strip and we
would be able to also delete any white
space on the right by changing this to
our strip or we could delete all the
white space altogether by just making
that strip and just to do a little bit
more completions type of thing why don’t
we cover formatting strings we could
also go puts full name or justification
and this is going to give us 20 spaces
then full name plus everything else is
going to come out to 20 spaces and let’s
say any additional spaces we have of
those 20 we want to put dots inside of
there we could do that and that’s going
to be right justified we’d also be able
to do left justified as well as Center
and it’s easier just to show you exactly
what this looks like rather than trying
to explain it and there you can say here
we have right justified here we have
left justified in here we have Center we
could all
so chop off the last character by just
typing in chop and we could also come in
and use chomp which we covered
previously by default is going to
eliminate a newline if it exists and if
there is no new lines going to do
nothing and if we want to delete the
last two characters for example we would
actually put whatever specifically one
that eliminated and there you can see
chop just cut off the last letter right
there and chomp cut off both of the
letters that we defined right there give
ourselves a little bit more room here
you could also have it delete specific
characters that you’d like deleted so
let’s just go full name delete and it’s
going to delete every occurrence of a in
that situation and we’d also be able to
go and create an array from a string by
just going full name and calling split
and in this situation we’re just going
to put two symbols there which basically
means it’s going to just split every
where there is a new character or you
can split everywhere there is a space
for example and let’s just copy this and
the difference you’re going to see here
in a moment here we’re going to put a
space inside here you could also put a
comments out there if you’d like if we
execute this is the one with just going
to show the each individual part of the
string in separate parts of the array
get more into arrays here in a second
and then here you can see it’s split
everything based off spaces and up here
you can see that it eliminated all the
A’s that we also covered and just to
reiterate this a little bit you’re going
to be able to perform string conversions
if you want to convert a string into an
integer
you just put two underscore I going to
convert it into a float to underscore F
and if you wanted to convert it into a
symbol which we’ll talk about a little
bit later to underscore symbol and then
finally if you’d like to see the most
common backslash is you’re going to be
able to use there they are okay so if
everything is an object inside of a ruby
we might as well talk about objects now
in object oriented objects using classes
and just like everyday objects every
object is going to have attributes which
we are going to call instance variables
as well as capabilities which we are
going to call methods now let’s say that
we have a class called
animal inside of it you can put
and initialize function and this is
going to be called anytime a new animal
object is going to be created and this
is where you would normally put default
values here we’re just going to say
creating a new animal and and that of
course I’m going to show you really easy
ways to create setters and getters
inside a ruby but for now I’m just going
to create a setter and getter let’s say
it gets passed a new name if you wanted
to set an instance variable inside of
Ruby you would put the @ symbol and then
name don’t need to do anything else with
it and this is going to assign that
value like that and of course we’re
going to want to put end there as well
we could then define a getter and you
just put @ name and that’s going to
automatically return that and put end
another way you could come in here and
get a value is def name and then just
put name inside there like that and
another way you could provide a setter
is go def name equal to new underscore
name and one of the reasons we use
getters and setters is to make sure that
bad data never gets in so let’s say we
want to make sure that the name that is
passed in is not a numeric number we
want to make sure we’re using characters
here we can just go numeric like that
and if it is a numeric we’re going to
say name can’t be a number something
like that else we’re then going to
assign the value that was passed in
there to our name instance variable and
here we will end the if and here we will
end the setter method and then finally
we’re going to end our class so that’s
how that all structures out now after
we’ve created this class we’ll be able
to come in here and create a animal
object so let’s say we want to create an
object called cat we would just call
animal and new and that’s going to
create that animal object we could then
go cat set name and pass in a name for
it we could then get the name of it cat
get name the alternative way of getting
name will just be cat and then just
typing a name which is normally what you
would use like I said I’m going to show
you a shortcut for generating getters
and setters in a second and in an
alternative way of actually setting the
name just be this and then let’s say we
want to type in this new name puts cat
name again and there you can see
creating a new animal and that’s the
initialize function it’s going to be
called every single time
new animals created and you can see all
the different ways that we are using to
set the name and get the name and
exactly how they work pretty much
exactly the same when I go and create
the new and improved dog class and here
I’ll show you the shortcut for creating
all your getter functions you’re never
going to type this in though because I’m
going to show you a way to generate them
all named in this situation is a symbol
which like I said we’ll talk about a
little bit later on and let’s say you
wanted to also have a weight instance
variable inside of here those are going
to create all of your getter functions
automatically if you wanted to create
all of your setter functions you just
again list all these different instance
variables you want to have and there you
go or you could create all your getters
and setters with one statement by just
typing attr accessor which is normally
what you’re going to do and then type in
your instance variables again and wait
there you go now we could come in here
and define another function called bark
which is just going to return a generic
bark and close that and then close your
class now we could create a dog dog
object like that do that up so we can
see it all at one place could then go
Rover name just to prove that we have
our getters and setters
just call him Rover output Rover on the
screen with Rover name and there you can
say Rover prints out on the screen just
like we set it now whenever we inherit
from another class you get all of the
methods as well as instance variables
automatically so let’s go and create
another class and we’ll call this German
Shepherd and how you inherit from dog in
this situation is just putting that
carrot symbol in there with dog and of
course you would be able to come in here
and inherit everything but also
overwrite so let’s say we went have loud
bark print out instead of generic bark
here you can do that and it close off
your class everything automatically goes
through let’s say we create a German
Shepherd called max German Shepherd
there he is again type new and you’ll be
able to come in here and define name
even though you didn’t define it inside
of the German Shepherd class because it
was inherited and when we talk about
printf printf is going to be able to do
some formatted printing for us so let’s
say we want our strings inside here
strings is going to be a percentage sign
and s now we can go goes percentage sign
s and then we
want to throw a new line inside of there
we would then be able to go max name and
Max bark and if we execute it you can
see everything works out now let’s talk
about modules modules are made up of
methods and instance variables just like
classes but they can’t be instantiated
which means you can’t turn them into an
object we can use most common reason
you’re going to use these is the to add
functionality to a class because we’re
only going to be able to inherit one
class when we’re creating a class but we
will be able to inherit multiple modules
let’s start off by creating a couple
modules here we’re going to create one
called human and how we create a module
is just go module and I’m going to call
this human remember if we want to
automatically have our getters and
setters set up for us access err
there we go and then let’s say we have
name height and weight there we go we
could then define a function inside of
it and if we wanted to output a specific
name for our specific object we’d use
self just like you use this and many
other programming languages and then we
could just have the name show up there
and runs close that off and just like
everything else to close off the module
we put an end there and I’m going to
call this human RB is the name save it
and let’s go and create another one this
module is going to be called smart then
we’ll put a function called act smart
inside of it and whenever that’s called
it’s going to return e equals mc-squared
for example and we’ll close that off and
we’ll close off our module and we’re
just going to call this smart RB save it
I’ll jump back over into our regular
class we’ve been using here or regular
file now if we want to allow access to
those modules we’re going to have to go
require relative at the top of our file
here and then type in what we want and
has to be in the same directory of
course relative again and we’re also
going to put smart inside of here we
could then create another module just
create a whole bunch of modules and this
one’s going to have a function called
make sound and whatever it’s called it
is just going to print out girl on the
screen and that and that this is just a
show you can have modules in different
places but you normally want them in
separate files it’s just easier to work
with
we would then be able to create a dog
class inside of here and if we want to
include that module we just go include
animal and end and you’ll see here we
can go Rover is equal to create a new
dog object like that and then Rover and
we could say make sound and there you
can see ger prints out on the screen we
could also create a class called
scientist and we could include our human
module inside of here just by going
include human we could also include our
smart module inside of here and if you
want your module to supersede so that if
a function is in both this class as well
as the module you are taking it from you
would use prepend instead of include and
we’ll go smart here then what we’re
going to do is we’re going to define a
function called act smart but remember
our function in smart is going to
supersede this one even though we
created it inside of here because we
used prepend instead of include and in
this one we’ll put a different version
MC let’s say squared like that just you
can see it and then we’ll close off our
class again now you can see if we create
Einstein is equal to scientist dot new
and we go and create a name Forum and
make that name is equal to Albert like
that we can print that out
Einstein just like that and we could
also go Einstein call the run function
inside of the human just to show that
that works and then go Einstein name
says Einstein dot act smart
save that and execute you can see right
here equals mc-squared shows up instead
of this and the reason why is we use
prepend right there and if you look up
here you can see the version that
actually prints out on the screen that’s
a way of using modules and classes and
objects and all a bunch of other
different things something else that no
doubt will come up people think about is
polymorphism and works a little bit
different inside of Ruby let’s say we
have a class called bird and it has a
tweet method tweet what we would do here
here is so that you know statically
typed languages use something called
duck typing to achieve a version of
polymorphism and the reason why they do
that is languages like Ruby pay less
attention to the class type versus the
methods that can actually be called from
an object so let’s say we have bird and
tweet just like we said what we would do
here is have bird type and we would call
tweet on that so the actual object
that’s being passed in here we would
then call it specific version of tweet
you’re going to see here in a second
what that looks like so we’ll go end and
end this class as well then we’re going
to create something else another object
called Cardinal or another class anyway
it’s going to inherit from bird and then
we’re going to put tweet inside of it as
well in this situation we’re going to go
and print tweet out on the screen when
that’s called and then let’s create
another one not a class called parrot
also going to inherit from the bird
class it’s also going to have its own
version of tweet make sure that’s
lowercase puts and whenever it’s called
it’s going to squawk there we are now we
can create a generic bird which is going
to be of bird type and what we’ll be
able to do to simulate the polymorphism
is called tweet and then pass in a
cardinal in this situation and new you
know you can go and create it create the
Cardinal object outside of here of
course and then we’ll go to eat and then
in this situation we’ll call parrot no
and if we execute that you’re going to
see the tweet tweet prints out for our
Cardinal which we have right here while
squawk prints out for the parrot right
there
so there’s an example of duck typing and
polymorphism inside of Ruby now I’m just
going to briefly cover symbols now
symbols inside of Ruby are basically
strings that cannot be changed and
you’re normally going to use them to
either conserve memory or to speed
string comparison and you would usually
use a symbol versus a string whenever
you need a string that’s value doesn’t
need to change as well as you need a
string in which you do not need access
to string methods they’re very commonly
used in hashes for keys and so forth
again we’re going to get into hashes in
a second symbol basically looks like
this and its value is whatever it is
right there
let’s just go and print it out on the
screen just so you can sort of see this
so let’s go puts and dark and then let’s
bring a couple of these guys in here
five those and also let’s convert it to
a string just to see what it looks like
and if we come over here and execute
you’re going to see Derek Derek
symbol which is the class type shows up
there as well as a unique object ID and
like I said we’re going to get more into
those as time goes by but you may also
remember a symbol here which you use
previously in which we automatically
generated our getters and setters inside
of our function look like that remember
type in weight as well symbols are used
a lot inside of Ruby and like I said
before they’re very often used as keys
inside of hashes since we mentioned
hashes won’t we talk about something
that’s very similar first called an
array well we have already seen a raise
let’s go and create a couple arrays here
a couple different ways you can create
an array you could call array new like
that you could create an it different
array by going array dot new and then
saying that we want five spaces in our
array or five little slots where we can
put stuff in that situation the default
value is going to be nil which means
pretty much not a value and we create an
array also by going array new and saying
that we want five spaces set aside and
the default value in this situation
would be empty and we could also go
create an array by actually passing
values and you can store anything in an
array you can store one you can put a
string inside of there if you’d like
there’s three or you could put float
inside of there it’s not going to bother
anything and let’s say we want to come
in here and print these out on the
screen just to see what they look like
there you go there’s empty empty empty
this is actually where we have nil which
is not a value and here we have empty
and here you can see that we printed out
all the different values that we stored
in our forth array now with arrays they
are going to start off storing things in
an index of zero which is very common so
if we just typed in two here you can see
the three shows up but that’s zero one
two that’s how we’re going to get all
those different values inside of our
array we would also be able to come in
and
earn to values starting at the second
index for example by just putting two
and two right there and I’m going to put
joint inside of here so we’ll join all
of our results together and separate
them with a comma and a space and there
you can see that’s how that worked out
we could also come and return values by
doing values underscore at and then
inside of here we could list we want the
zero index the one index in the three
for example and once again we’re going
to join those together with a common
space and put a dot inside of there
because that is a method execute and
there you can see it returned those
nicely for us we would also be able to
come in here and add a value to the
beginning of our array by using on shift
and then whatever value we want to put
in there let’s say we want to put zero
inside of there we could also go and
remove the first item in an array by
going shift and then there’s not going
to be anything because it’s just
removing an item we could add one
hundred and two hundred for example to
the end of array by just going push and
play around with these on your own to
see exactly how they work and that’s
going to add two values to the end while
if we would go in and type in pop that’s
going to remove one item from the end of
our array we could also come in here and
concatenate or join two arrays we could
create a brand new right here if we’d
like so we’d say we wanted to put 10 20
and 30 that’s going to add that to the
very end of our array and there’s a
whole bunch of different methods we
could use if we wanted to get the size
rate for and type in size put our braces
there and let’s say we want to convert
that to a string there you go ray size
is equal to eight we could also check
that an array contain the value so it
contains 100 for example and here
instead of size we’re going to put
include and question mark and then
whatever you’re searching for 100 for
example we could check how many of those
matches we have so how many 100s for
example and then take the size out of
here and instead put count inside of
there and specifically what we’re
looking for
and we could also check to see if the
array is empty by just going that and
then we’re going to type in empty
question mark 4.2 a string and there you
can see all those come back we could
worse just like I showed you with join
before convert our array into a string
puts array for dot join and then however
you want those combined into your string
P is pretty cool because it’s going to
allow us to print out the entire array
on the screen in just one way which is
kind of neat and we could also print out
our whole entire array in a loop
situation by putting each inside of
there and we saw this before at symbol
let’s say we want each of these
individual values in our array to
temporarily be stored in a variable
called value and then we could go puts
and value as it’s suiting through there
and then end that and if we execute all
those things show up right there on our
screen so pretty cool so that’s pretty
much everything you want to know about
using arrays while we look at a close
cousin to array called hashes and a hash
is just a collection of key value pairs
so let’s go and create ourselves a
number hash for example we would use
curly braces in this situation and first
you’re going to have your key instead of
indexes you have keys and then you’re
going to put that little symbol right
there and then whatever you want the
value to be associated with that and
then you can put a comma and then let’s
go and say we want another one to be
called golden put that little symbol
there 1.618 and then let’s say we want
another one to be e little symbol 2.718
and that is how you create a hash inside
of Ruby now let’s go and use them
we could go puts to get the actual value
number hash and let’s just pass in well
make sure you put square brackets here
square brackets and whatever the key is
and that’s going to print that out on
the screen for you so we’re just using
keys instead of indexes which are
sometimes easier to use say we want to
create a superhero type of hash and of
course you could have these all be on
separate lines just so they show up
easier on your screen and go like that
do whatever you want and of course
you’re going to be able to call
superheroes again and pass in Clark Kent
for example make sure you have the key
exactly the same though and there that
shows up a Superman you’ll be able to
come in and add an individual new key
and value to your hash by just going
superheroes and then defining whatever
you want the key to be right like that
automatically going in and adding in a
new value for that key there it is it’s
in there now something else is you could
add a default key value which is very
useful so that if the user goes and
looks for something that doesn’t exist
inside of your hash it’s going to print
out something useful like no such key if
it can’t find anything which is like I
said pretty useful so you go in here and
say I want to get whatever is in sample
hash with the key dog it doesn’t exist
and you see no such key comes up we
could then come in and create some super
heroines hashes right like this you
could then combine these with update by
just putting in super heroines instead
and whenever you’re using update this is
considered a destructive merge which
means if there’s any duplicates they’re
going to be eliminated you could instead
use merge which would be a non
destructive which would keep all the
keys and values even if they matched
normally you’re going to use update
because you wouldn’t want any
duplication inside your hash I’ll just
cost confusion now if you want to go
through exactly how to print all of
these out we would just go superheroes
and we would use each again do you could
get the keys and values by just putting
in key and value and then close that and
then we’ll go puts and then we go key
and we need to convert that to a string
plus put some separation between these
and a value and end execute you can see
all of them print it out real nice
and of course there’s a whole bunch of
different functions available for hashes
as well we could come in here and check
that our superheroes hash has the key of
Lisa Morel like this also be able to
come in and check if we have a value by
passing in a value so there’s Batman and
you can see right there’s Batman this is
the key that’s the value and of course
we could check if it’s empty as well as
whatever the size is for it if we
execute that you can see all those come
out there and the only other thing I
could think of is how would you delete a
key you would go in here and go
superheroes and delete and you could
pass in whatever would be a matching key
and that’s going to delete that for you
if we wanted to double check that that
actually was deleted
in here see if the actual value for the
size changed and yes you can say five
and four so those are all the main
things you’d ever want to know about
using hashes inside of Ruby so why don’t
we go and check out enumerables now a
class that includes the enumerable
module is going to gain collection
capabilities sort of like we saw with
arrays and hashes now let’s just come in
here and create one let’s call it menu
and let’s say include enumerable just
like this one requirement however is if
you’re going to inherit this you’re
going to have to provide a function that
is called each now we’re going to put
inside of here all the different things
that we’re going to have in this
enumerable so if we have a menu we’re
going to have pizza and you’re going to
find all these different options by
putting yield inside of here for each of
the possible options and salad and water
and bread is keeping it simple courses
is going to end with end and then the
class will end with end will then be
able to go and you options and create a
new menu just by using new just like
we’re used to we can in cycle through
all those by going menu options and
guess what each do again just like we’ve
seen many times temporarily held in item
and we could put puts and we could have
an automated sort of waitress here would
you like and then put in an item and put
end there we go and ask would you like
all the different things on our menu we
could then check to see if we have a
pizza for example so menu options go
find then inside of here well make sure
you use curly brackets in a situation it
would say item and we would check if any
of these items is equal to pizza and if
it does find a match it’s going to print
that out we do all kinds of weird things
let’s say that we wanted return items
that are 5 letters in length we could
come in here and say select and this is
going to cycle through all these
different options so we could say so
item item size less than or equal to 5
likewise we could use reject instead of
select reject and it’s going to reject
anything that meets those options we
could also come in and print out the
first item we have we could also come in
and print out the first two by using
take like this we could return
everything except for the first two by
using drop it’s not going to affect the
enumerable in any way just going to show
those and onwards and onwards we could
also menu options get the minimum item
we could also get the maximum item and
that’s going to pend upon alphabet order
or whether you have numbers or letters
or whatever we’re also going to have
sorting options and we could even return
every single option in reverse order if
we’d like so go reverse each just to be
kind of silly here there we go execute
and you can see everything prints out
there on the screen so there is pretty
much everything you want to know about
enumerables and we’re pretty much done I
figure why don’t we just cover the file
object because it’s very useful as you
saw before if you want to create a new
file that you want to write to use the
file object followed by new and then you
would provide a name that you would like
to have assigned to this new file you
create I want to be able to write to it
just put a W inside of there and there
you go you have a file you can write to
if it’s not created it will be created
then you can just use puts to
automatically go in and throw some
information into your newly created file
let’s just throw in three authors after
you open it and put things in the file
you would of course want to close it you
want it to output everything that is an
assigned to this file object you would
just use read and then pass in the file
that you wanted to pull information out
from just check to make sure all that
works and yes indeed it does if you want
to open a file for appending just use
the file object again followed by new
and authors out and then in this
situation instead of a double if you
want to append to the end of the file
you would put an A inside of there then
come in and throw in a new author that
you may have forgotten Danielle Steel
for example and of course close that
file again then if you wanted to read
from this file again just to make sure
that it updated you can see that
Danielle Steel is now there this didn’t
copy this multiple different times just
shows that way because we have this
other read here then let’s go and create
another file equal to file well make
sure that’s uppercase no and let’s call
this one off
there’s info out and it’s a new file
that hasn’t been created let’s make it
writable and in this situation we’re
going to put a whole bunch of
information in here so we’re going to
have the author’s name their language
the type of poetry or types of books
they wrote and the number of items sold
on our screen close our file and then
let’s say we want to cycle through the
data to write out sentences based off
the data that’s stored inside of there
well you go file open and then we could
type in author info like this out there
is the name of our file do we’re gonna
be able to use do again and we could say
each one of those lines is going to be a
record and then we could go record each
do we could have each line of that
document go inside of the item here we
could then split each line into four
parts based off of commas so we’ll say
name will be the first one lying will be
the next one specialty will be the next
one and sales will be the next one is
equal to item this item represents the
whole entire line and we can say chomp
which means all that information is
going to be split based off of commas
and then after we split all that stuff
we could go put and make some neat
things let’s say name was a and we could
say what type of book make sure you have
the curly brace clothes there was a and
we type in language author that
specialized in and whatever their
specialty was and then say something
like they sold over and whatever the
sales were for their books and then
books and then after that we want to
close this off and then close this off
and if we save that and jump over here
you’re gonna see when Shakespeare was an
English author specialized in plays and
poetry they sold over 4 billion books so
there you go guys there is a heck of a
lot of information about Ruby please
leave your questions and comments below
otherwise till next time
Please follow and like us:

Be First to Comment

Leave a Reply