Programming With Ruby Episode 10, Objects and Modules

Part 1:

Part 2:

Covered In This Episode

  • Variable Scope
  • Class creation
  • Open Classes
  • Class Inheritance
  • Modules

Transcript:

Hello Everybody and welcome to Programming With Ruby Episode 10,
Objects and Modules. As always, I’m Tyler and this video is brought to
you by manwithcode.com

Variable scope will be explained.

In this episode I will be going over class creation, I touched on this
before but that was a while ago and I will also be going more in-depth

I will be teaching you what class inheritance is.

You will also find out what open classes are, and why they are useful.

You will learn what modules are, and how and when you should use them

Lets get started!

Variable Scope

I taught you about variables earlier, but I need to go a little more
in-depth for you to be able to write real applications, and not be
confused by some mysterious errors.

What is a variable scope? a variable scope is where the variable is
available for use in the program. The code in classes and methods that
you define have a different scope than the code outside
them. Different scopes are introduced when classes and methods are
defined.

There are 5 different types of variables:
1. local variable ex: variable
2. instance variable ex: @variable
3. class variable ex: @@variable
4. global variable ex: $variable
5. constant variables ex: VARIABLE

A local variable is available in the scope in which it is defined. An
instance variable is available in the instance of the class it was
defined. A class variable is available from any instances of that
class. A global variable is available anywhere. A constant is
available anywhere, but can only be changed within the scope it was
defined.

Class Creation

As mentioned in episode 4 you define classes like this, don’t forget
that classes must start with an upper case letter:

class MyClass
end

and create them like this:

variable = MyClass.new

You can define methods inside the class:

class MyClass
    def hello
        puts 'Hello!'
    end
end

If you define a method named ‘initialize’, that method is run when the
class is instantiated. This is very useful in many situations, like
creating a screen in a game or connecting to the database in a web
application. This is also the usual place for defining instance variables

class MyClass
    def initialize
        @database = connect_to_database
    end
end

A method defined with ‘self.’ in front of it’s name is called a class
method, because the method is available outside of the class, and you
don’t have to instantiate an object. These can be useful for times
when you don’t want create objects, or want certain information about
all the instances of a class.

class MyClass
    def self.game_objects
        # Return all objects in the game
    end
end

Open Classes

So now that you know more about creating classes, I would like to call
your attention to a very useful feature of Ruby, Open Classes.

The term Open classes means you have the ability to add or substitute
code in a class that is already defined. This is quite easy to do too,
all you have to do is define a class in the same way you always do,
just with a pre-existing class. You only have to define what you are
adding, or overwriting, you don’t have to define the WHOLE class
again.

Take for example, the String class. This class (obviously) is the
class from which all strings are created. Lets say, for example that
you had some code that took a string, and gave back an array that had
each word in it. You could do this:

def words(string)
    string.scan(/\w[\w\'\-]*/)
end
words("Hello World") #=> ["Hello", "World"]

But it looks a lot nicer, and is more object-oriented if you do this instead:

class String
    def words
        scan(/\w[\w\'\-]*/)
    end
end
"Hello World".words #=> ["Hello", "World"]

You can probably see why this can be useful.

Be careful though, if you override existing functionality, you run the
risk of breaking that functionality in your code, and all the external
code your project uses.

Class Inheritance

Lets say you are making a video game. In that game you will have many
different types of enemies.

Now, odds are that all your enemies will have stuff in common. They
probably will all have health, ammo, etc. They all will have to draw
themselves on the screen, animate when they move, etc.

So you can see that with many different types of enemies, you would
have to have lots of duplicate code in each class. This is solved via
class inheritance. Class inheritance allows you to write one class
that contains all the common code. Then when you create other classes
you can specify that those classes will use (inherit) that common
code.

You specify if a class is inheriting from another by following the
class name, with a less than sign followed by the name of the class
you are inheriting from.

You can also re-implement some of that common code, if needed.

For example:

class Enemy
    def draw
        # Drawing Code
    end
end

class Soldier < Enemy
    def move
    end

    def shoot
    end
end

class DifferentEnemy < Enemy
    def draw
        # Changes the draw functionality, only for this class
    end
end

Another thing to keep in mind, if you redefine the initialize method
in your inherited class, you must call the super method.

Modules

Modules are like classes, except they can’t be initialized, and every
method has to be prefixed with “self.” like class methods.

This limitation in functionality may make you wonder when modules are
ever useful. There are actually only a few times. First is to keep
parts of your code separated. The more important second reason is when
you are creating a library of code for others to use. This is so the
functionality in the library isn’t stepping over or redefining classes
you have already defined (if they happen to have the same name).

You define modules just like you do classes, except using the module keyword:

module DataVisualizer
    class Grapher
    end

    class Plotter
    end

    def self.data_compatible?
    end
end

To access methods that modules define you simply do:

module MyModule
    def self.x
    end
end
MyModule.x

To access classes defined by modules, you have to use double colons:

module DataVisualizer
    class Grapher
    end

    class Plotter
    end
end

DataVisualizer::Grapher.new

That’s all there is to know about modules, meaning this is the end of
the episode!

Please donate, those these videos are free, it costs money to make them.

If you have any questions comments or suggestions about anything
related to Man With Code or the Ruby tutorials, you can leave a
comment on this page or email me at tyler@manwithcode.com

Than you very much for watching, goodbye!

Programming With Ruby Episode 9, Flow Control

Part 1:

Part 2:

Covered in this episode:

  • Code Blocks
  • if, else, unless
  • case, when
  • while, until, for loops

Transcript:

Hello everybody and welcome to Programming With Ruby Episode 9, Flow
Control. I’m Tyler and this video is brought to you by manwithcode.com

So far all of the programs and code that I have shown you has been
completely linear. There has been no way to loop based on a condition
or do something based on what the user inputs.

In this episode I will be showing you how to do all this, and I will
also be explaining to you what a code block is, since I’ve been
mentioning them in almost every episode previous to this.

This episode is REALLY LONG! Feel free to pause the video and think
about what’s been said or try out code yourself.

Code Blocks

Throughout the previous videos, I’ve been telling you about code
blocks, I’ve also been telling you I’ll teach you what they are in a
later episode. That episode has finally come.

Code blocks look something like this:

my_array.each do |item|
    puts item
end

or like this:

my_array.each { |item| puts item }

Both of those actually do the same thing! The .each method takes a
block as an argument. The block is what is between the do and end
keywords, or the curly braces, depending on which format you use.

The item between the pipe characters (which is above the ENTER key) is
the variable the .each method gives you (in this case the item in the
array).

The rest of the code block is just normal Ruby code. Not so complicated, eh?

(Keep in mind that there are more metheds besides .each that take code blocks)

If, Else, and Unless

A basic if statement would look like this:

x = 3
if x < 5
    # Do something
end

The “x < 5” is the condition that has to be true for the code to
run. If that condition is true, the code between the “if” and “end”
keywords is run.

There are many different conditional operators you can use:

==
<
>
<=
>=
!=

Just be sure to keep in mind that the “is equal” operator uses two
equal signs, not one.

If you would like code that is run when the condition is false:

x = 3
if x < 5
    # Do something if true
else
    # Do something if false
end

In a similar way you can execute code if the first condition is false
but a second is true:

x = 3
if x < 5
    # Do something if true
elsif x == 3
    # Do something if the first is false and this is true
else
    # Do something in all are false
end

In a different way you can only execute the code if two conditions are true:

x = 3
y = 2
if x == 3 and y == 2
    # Do something
end

You can also only execute code if one of any conditions are true:

x = 3
y = 4
if x == 3 or y == 2
    # Do something
end

There is also the evil twin brother of if, unless:

x = 3
unless x == 3
    # if x is 3, this code will not run
end

You can chain all of these together in almost any way you choose.

Case, When

Another way to evaluate conditions is using case, when:

x = 3
case x
    when 1 then
        # do something
    when 3 then
        # do something
    else
        # do something if none are true
end

You can’t do many complex conditionals, but it can be nicer than a
long chain of if, else’s

while, until, and for loops

Similarly to the above if statements, while, until, and for loops will
execute code based on a condition, but they will do it multiple times.

while:

x = 1
while x < 5
    x += 1
    puts x
end

Similar to the relationship between if, and unless. while has an evil
sister, until

x = 1
until x > 5
    x += 1
    puts x
end

There are also for loops, which allow you to iterate over something

foods = ["ham", "eggs", "cheese"]
for food in foods
    puts food += " is yummy!"
end

There is also .each, for’s evil stepchild:

foods = ["ham&", "eggs", "cheese"]
foods.each do |food|
    puts food += " is yummy!"
end

Concrete Example

A menu system

input = ""
until input == 'quit'
    puts "
Menu
(1) Hi!
(2) Credits
(3 or quit) Exit
"
    input = gets.chomp!
    case input
        when "1" then
            puts "Hi!"
        when "2" then
            puts "Written By: Tyler"
        when "3" then
            input = 'quit'
        else
            puts "Invalid input"
    end
end

Lets break it down.

First we set the input variable to an empty string (so the second line
dosen’t give us an error)

Then we use an until loop that quits when input is equal to ‘quit’

Next we print the menu (which is unindented so it doesn’t print to the
screen indented)

After that we get input from the user, use .chomp! to remove the
newline character created from pressing ENTER, and put the input into
the input variable

Then we have a case statement, when “1” we print “Hi!”, when “2” we
print who it was created by, when “3” we quit, otherwise we print out
“Invalid input” to tell the user they entered something wrong.

This brings us to the end of the video.

If you like these videos please donate, because I’m doing this all for free

If you have any questions, comments, or suggestions, you can leave a
comment on this page. Or you can email me at tyler@manwithcode.com

I covered a lot of material in this episode and I urge you to watch it
again, go to the original post and look at the code (link is in the
description) and write some code yourself.

Thank you very much for watching, goodbye!