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!

Programming With Ruby Episode 8, Hashes

Covered In This Episode:

  • What are Hashes?
  • Hash Creation
  • Hash Accessing
  • Hash iteration
  • Hash Methods

Transcript:

Hello Everybody and welcome to Programming With Ruby Episode 8,
Hashes. I’m Tyler,and this video is brought to you by, manwithcode.com

In this episode I will be telling you what hashes are, how you can
create them, access them, and iterate over them. Finally at the end I
will show you some useful methods that hashes have.

What Are Hashes?

Hashes are like arrays, which you learned about in the previous
episode. Except that they have no order, and instead of being accessed
by an index number, they are accessed by what is called a key (which
can be anything). That key points to a value, which is the actual data
inside the hash

Arrays are used for lists of data, where hashes are used to relate
data. I may have a hash where the keys are my friend’s names, and the
values are their birthdays.

Hash Creation

Similarly to how arrays are created with square brackets, hashes are
created with curly brackets:

my_hash = {}

Items are defined like this:

birthdays = {"Amy" => "May", "Dakota" => "January"}

Each key-value pair are separated by a comma, and their relation is
defined with =>

Accessing Hashes

You can access hashes in almost the same way you access arrays, except
by using the key value, instead of an index number:

brithdays["Amy"] #=> May

You can define new keys and values:

birthdays["Zack"] = "April"

Iterating Over Hashes

Hashes have an each method like arrays do:

my_hash = {"cat" => "hat", "dog" => "log"}
my_hash.each do |pair|
	puts "Key: " + pair[0]
	puts "Value: " + pair[1]
end
#=> Key: cat
#=> Value: hat
#=> Key: dog
#=> Value: log

They also have each_key and each_value which let you iterate over each
key or value in a similar way.

Useful Hash Methods

delete(key) deletes a key-value pair
empty? True or False if the hash is empty
keys returns the keys
values returns the values
size how many key-value pairs there are

That wraps it up for this episode!

Please donate, or I will stop making these videos. There should be a
link to donate to the right of this video.

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

Thanks for watching, goodbye!

Programming With Ruby Episode 7, Arrays

Covered In This Episode:

  • What Aarrays Are
  • Array Creation
  • Accessing Arrays
  • Array Iteration
  • Other Array Methods

Transcript:

Hello everybody and welcome to Programming With Ruby Episode 7,
Arrays. I’m Tyler. And this video is brought to you by manwithcode.com

In this episode I will be telling you what arrays are, how you can
create an array in ruby. How to manipulate arrays by accessing them,
iterating over them, and by showing you a few useful methods they
have.

Lets get started!

What are Arrays?

Arrays are a type of variable. Think of an array as a list. This list
can hold anything, names, numbers, objects, anything. Objects in the
array have a number, depending on what place they are in the
list.

Because computers start counting at 0, the first element in the
array is 0, instead of one.

Array Creation

This is how a variable is defined in ruby:

x = []

This is an empty array, if we wanted an array with something in it:

todo_list = ["Cut Grass", "Buy Food", "Fix Tom's Computer"]

Each bracket represents the start and the end of the array,
respectively. Each item in an array is separated by a comma.

Accessing Arrays

Now that you have created an array, how do you go about accessing each
item?

I told you earlier that each item had a number, so to access the first
item in the array you would do:

todo_list[0] #=> "Cut Grass"

You can also add items to an array in a similar way

todo_list[3] = "Go Skydiving"

Another way to add items is to use +=, which you may recognize from
previous tutorials

todo_list += ["Eat Sandwich"]

Don’t forget that if you use += that the item your adding has to be
between brackets

You can also use ranges to access elements in the array. ranges are
used in a similar way that you normally access arrays, except ranges
look like this:

todo_list[0..2] #=> ["Cut Grass", "Buy Food", "Fix Tom's Computer"]

The 0 is the start number and the 2 is the end number. you can also
use -1, which is the end of the array:

todo_list[3..-1] #=> ["Go Skydiving", "Eat Sandwich"]

Array Iteration

If you want to loop over each element of an array you use the each
method:

numbers = [1, 2, 3, 4]
numbers.each do |number|
puts number * 2
end
#=> 2 4 6 8

You can do the same thing, but turn the output into an array with the
collect method:

numbers = [1, 2, 3, 4]
numbers.collect do |number|
number * 2
end
#=> [2,4,6,8]

Other Array Methods

Now I’m going to show you some useful methods arrays have!

empty? tells you if an array is empty
sort sorts the array (alphabetically)
reverse reverses the array
delete deletes a specified item from the array
delete_at deletes whatever is at that index in the array
find finds an item with the specified value
inspect returns the way an array looks in code, instead of its values, this is useful for puts my_array.inspect
length how long the array is

That’s it for today’s episode

Please don’t forget to donate, the link should be to the right of this video

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

Thanks for watching, bye!

Programming With Ruby Episode 6, Strings

Covered in this episode:

  • String Literals
  • String Expressions
  • String Methods
  • Regular Expressions
  • Getting User Input (gets)

Transcript:

Hello Everyone and Welcome to Programming With Ruby Episode 6,
Strings. I’m Tyler, your presenter. This is brought to you by
manwithcode.com

In this episode I will be telling you what string literals are. I will
show you expressions you can use with strings, which are similar but
still different than expressions with numbers. I will show you useful
methods strings have. I will show you how to use regular
expressions. Finally I will teach you how to get input from the
user.

On to the Code!

String Literals

According to wikipedia, string literals are the representation of a
string value within the source code of a computer program. For
example:

puts "Hello World" # Hello World is the string literal

String Expressons

The only string expressions are the plus and multiplication sign. The
plus sign connects strings together, the multiplication sign repeats a
string a certain number of times.
Let me show you how it works:

"Hello " + "World!" #=> "Hello World!"
"Hello " * 3 #=> "Hello Hello Hello"

String Methods

Here are some useful String methods:
empty? tells you if you are dealing with an empty string
length tells you how long a string is
each_char lets you iterate over each character
capitalize capitalizes the first character
upcase makes all characters upper case
downcase makes all characters lower case

Regular Expressions

Regular expressions are a way to match elements in other strings. It
is easier to show you than to describe to you, so here we go!

The simplest is substitution:

"Hello World".sub("Hello", "Goodbye")
#=> "Goodbye World"

But if you have more than one hello:

"Hello Hello Hello".sub("Hello", "Goodbye")
#=> "Goodbye Hello Hello"

This happens because the sub method only replaces the first occurrence
of “Hello”. The gsub method fixes this:

"Hello Hello Hello".gsub("Hello", "Goodbye")
#=> "Goodbye Goodbye Goodbye"

What if you want to manipulate parts of a string using regular
expressions. The scan method is what you want!

# /n means new line
"Who are you".scan(/../) { |x| puts x }
#=> Wh\no \nar\ne \nyo
# With no whitespace:
"Who are you".scan(/\w\w/) { |x| puts x }
#=> Wh/nar/nyo

Regular Expressions are a vast topic that I can’t completely cover
here, so do a Google search to find out more.

Getting User Input

You can get user input with the “gets” method:

a = gets
# The user inputs: I like pie
puts a #=> "I like pie"

That wraps it up for todays episode.

Don’t forget to donate, the link is to the right of this video

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

Bye!