Programming With Ruby Episode 11, Ruby Projects

Covered In This Episode:

  • Finding projects (GitHub, RubyForge)
  • Using Rubygems
  • Using the code

Transcript:

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

Despite what the name may imply, this episode is not about making
projects in ruby, but finding and using projects other people have
made. I will be showing you rubyforge.org and github.com, both places
have many different and useful projects hosted.

I will also be showing you how to use rubygems, arguably the easiest
and most popular way of installing, managing, and keeping up to date
various ruby libraries, tools, etc. which rubygems calls gems.

And finally you will learn how to use the code you find!

Lets get started!

Finding Projects – Rubyforge

Rubyforge is one of the most popular hosting sites for ruby
projects. (It is also where most gems are hosted)

Just navigate over to http://rubyforge.org to get started

If you want to find a project, you have a few options. First is the
search box located at the top right of the website.

Second is the project tree where you can find projects by the category
they are in.

Third is the most popular projects on the homepage, which can be
helpful from time to time.

If you find a project that you like, you can download it, or install
it as a gem if it is available. Both of which will be covered a little
later in this tutorial.

Finding Projects – GitHub

Github is another project hosting site, that easily lets developers
collaborate using the version control system, git. Github has been
gaining a lot of popularity with Ruby programmers lately and you can
find many Ruby projects here.

GitHub is located at http://github.com

GitHub has search functionality, and most popular like Rubyforge, but
it is a little more comprehensive.

GitHub also offers nice graphs and many download options depending on
your needs.

Using Rubygems

To start using rubygems, first you have to install it. If you
installed via a one-click installer you probably already have it. To
check if you have it installed, open your command prompt and enter
“gem”. If nothing comes up, it is not installed.

If you are on Debian or a variant of it (such as Ubuntu) this command
will get you rubygems: sudo apt-get install rubygems

Otherwise go to http://rubygems.org/ and download rubygems from there.

After you’ve installed, run the command:
gem

to make sure the installation succeed. If not you may have to add
rubygems to your PATH, a quick Google search will tell you how.

For this example I you will install the gem hpricot, which parses HTML.
simply use the command:
gem install hpricot
or
sudo gem install hpricot

It should install successfully, and now you can start using it in your code!

But before we do that, I would like to show you a few more features or rubygems.

“gem list” lists all the gems you have installed
“gem uninstall gem” uninstalls the specified gem
“gem update” updates all your gems
“gem help commands” shows all commands that rubygems has, so you can
explore on your own!

Using the code

Now that you have installed a gem, or downloaded a projects source
code, you can use it in your own programs.

To obtain access to an installed gem, or the source file add the
following line to the top of your program:

require 'rubygems'
require 'name' # Name can be a gem or a source file

if you are just using a source file, you don’t need to require rubygems
example:

require 'rubygems'
require 'hpricot'

If you are loading a file that can change, use load:
load ‘name’ # Name can be a gem or a source file

Note that I said source file. This means that you can separate your
own code into different files and load them in using the load or
require methods!

Now we have reached that sad sad time, when the episode starts ending.

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

Please do not forget to donate, a small $5 or $10 donation will help
more than you realize!

Thanks for watching, Goodbye.

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!