Programming With Ruby Episode 13, Basic I/O

Covered in this Episode:

  • Defining I/O
  • Files
  • Directories

Transcript:

Hello Everybody and welcome to Programming With Ruby Episode 13, Basic
input output. As always, I’m Tyler and this video is brought to you by
manwithcode.com

In this episode I will be defining what exactly input/output is, You
will also learn how to work with files and directories in Ruby

Lets get started!

Defining I/O

So what exactly is I/O or input/output. Basically Input is any data that
you receive from the user, and output is what data you give to the
user, usually based on what input the user gave you.

In this episode you will be seeing I/O as working with files and
directories. You have already worked with I/O previously when we
talked about getting strings from the user (gets) and printing string
to the screen (puts)

Files

There are a couple of ways to start working with files. The first is
by using File.new:

my_file = File.new('file', 'r')
my_file.close

File.new opens the file (the first parameter), for the specified mode
(the second parameter)

The file name you use can be either just the relative file name
(notes.txt) or the full path to the file (C:\Documents and
Settings\Tyler\My Documents\notes.txt). Just remember that if you use
only the file name, that file must be in the same folder your program
is located in!

The mode defines how you are going to use the file you’ve opened. In
the example ‘r’ is used. Which stands for read, meaning we are only
going to read from the file.

‘w’ is write meaning we are writing to the file specified, be careful
when using write mode, as the whole file is cleared when it is opened.

‘a’ is append, which is similar to write, except instead of clearing
the whole file, it appends all written data to the end.

All the different modes can have ‘+’ at the end of them, which opens
up both read and write functionality. (ex: ‘w+’)

Now you know how to open a file, how exactly do yo go about writing to
it? By simply using puts and print, like you did when outputting data
to the screen, except they output data to the file!

my_file = File.new('example.txt', 'w')
my_file.puts "Hello World!"
my_file.close

If you want to read from a file you can use File.read:

my_file = File.new('example.txt', 'r')
puts my_file.read
my_file.close

You can also pass in how many characters you want to read as a parameter.

If you would rather have the lines of a file in an array, you can use
file.readlines.

If you are unsure a file exists you can simply use File.exists?:

File.exists("notes.txt")

Now it is important to note that every time I am done using a file I
call the .close method, why do I do this? Because if you don’t close
your access on the file, it can become unusable by other
programs. Also, your computers operating system might not write the
changes you’ve made to the file, until your program has released its
hold on it.

As an alternative to using file.close every single time, we can use
File.open, instead of File.new. File.open lets us use the file in a
code block, at the end of the code block, the file is closed
automatically.

File.open('hello.txt', 'w') do |file|
    file.puts "Hello World!"
end

There is a whole lot more you can do with files in Ruby to learn more
go to http://ruby-doc.org/core-1.8.7/index.html and find the File and IO class

Directories

You can work with directories (also known as folders) in Ruby using
Dir. You can create directories with Dir.mkdir:

Dir.mkdir("Hello")

You can get an array of all the files and directories that are in the
current directory with Dir.entries:

Dir.entries('.')

Keep in mind that . is your current directory, and .. is the directory
one level above the current one. Also, like files you can specify the
relative path or the full path.

There is also another method similar to Dir.entries, Dir.foreach. They
are essentially the same, except foreach allows you to iterate over
each item in a code block.

Dir.foreach('.') do |entry|
    puts entry
end

Like Files, there is a lot of material I couldn’t cover to learn more
go to http://ruby-doc.org/core-1.8.7/index.html and find the Dir class

This brings us to the end of the episode.

If you like these videos please donate.

And if you have any Questions, Comments or Suggestions, you can leave
a comment in the comment box below, or email me at
tyler@manwithcode.com

Thank you very much for watching, goodbye.

Programming With Ruby Episode 12, Documentation

Covered In This Episode:

  • Comments
  • RDoc

Transcript:

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

In this episode I will be talking about documenting your code, more
specifically with comments, and using the tool rdoc.

This should be a short show, so lets get started!

Comments

You’ve seen comments throughout these video tutorials. They were the
lines with the hash mark that are ignored by Ruby.

Comments are generally used to explain code to other developers
(including yourself). Ruby already makes code very easy to understand
in the first place. You can also help this by naming your methods and
variables sensibly. But there are times when this is not enough.

Sometimes you end up doing something very complicated, such as a long
regular expression, some SQL magic, or any other possibly difficult to
understand piece of code. Those can be times when comments are needed.

Comments are also needed for when you are making code for other
developers to use. When they are using your code and not developing it
along with you, they can care less about finding how it works. They
just want a comment that can tell them what your class/method/piece of
code/whatever does, and how to make it do it.

Tools like rdoc can help you make your code’s documentation even
better, and that is what we are going to talk about next.

Rdoc

Rdoc should be installed already from when you installed ruby. If not
you can install it via rubygems or your platforms package manager.

Rdoc is a tool that generates very nice looking documentation for your
projects.

First just run the command rdoc in a directory with code files in it.

rdoc will create a folder named “doc” and your documentation will be
that folder. If you go into doc and open up index.html in your
browser, you will see the generated documentation.

You will probably notice that rdoc didn’t pick up any of the comments
inside your code, only those right above the definitions of classes,
methods, or modules.

You may also notice that the descriptions might not be formatted very
well. You can spice it up by using rdoc markup found at:
http://rdoc.rubyforge.org/RDoc.html

I’m not going to go too much farther into rdoc, as it is not an
essential tool for development. It can be, however, very useful. So
please take some time to learn more about it!

This brings us to the end of the show.

Please don’t forget to donate!

If you have any questions, comments, or suggestions you can leave them
in the comment box below or email me at tyler@manwithcode.com

Thank you very much for watching, goodbye!

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!