Programming With Ruby Episode 15, Error Handling

Covered in this Episode:

  • What are errors
  • What is error handling
  • begin…end
  • rescue
  • ensure
  • raise

Transcript:

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

In this episode you will learn what exactly errors are, and what error
handling is. You will also be learning how to use the begin…end,
rescue, and ensure keywords, as well as the raise method.

Lets get started!

What are Errors?

There are two types of problems with programs. #1 is bugs, and #2 is
errors. You’ve most likely heard of both of these types of problems
before. But what are they?

Bugs are more subtle problems, the program still runs and acts
normally, but it may be outputting the wrong data, or messing
something else up. It is completely up to the programmer to find these
bugs.

Errors actually stop the program from running, or at least running all
the way through. There are ways of handling most types of errors,
which you will be learning about in this episode.

What is error handling?

It is possible to catch some types of errors, which when left alone,
would otherwise result in your program crashing.

Error handling is the process of catching those errors, and usually
doing something about them, like informing the user, or executing on a
contingency plan.

There are many things that can create errors, such as trying to read
from a file that doesn’t exist, a user entering bad data, trying to
call a method that does not exist, and the list goes on.

Some errors you can combat by using methods like File.exists? to check
if a file exists before trying to open it. But there are other cases
where this is not an option, or where you prefer to handle the problem
a different way. In this episode I will show you how.

Real Code

Error handling starts with the begin…end block which looks like this:

begin
    # Code here
end

In that block is where you put the code that has the possibility of
generating an error. That block in itself doesn’t do anything, to
actually handle the errors, you need to use the rescue keyword.

begin
    # Possibly error inducing code here
rescue
    # What to do if an error happens
end

What ever is between “rescue” and “end” will be executed if an error
occurs. But what if you have the potential for multiple errors? Then
you must use multiple rescues specifying the error the handle:

begin
    # Possibly error inducing code
rescue ArgumentError
    # If ArgumentError is raised
rescue NoMethodError
    # If NoMethodError is raised
end

What if you don’t know the exact name of the error? Either create the
error yourself and look at the output when the program crashes. Go to
http://ruby-doc.org and find all classes ending Error. Or consult
http://www.zenspider.com/Languages/Ruby/QuickRef.html#34

Now lets say you want something to happen regardless of whether or not
the code generates an error. Say maybe you have to close a file, or
end your connection to a database. Then you would want to use ensure!

begin
    # ...
rescue
    # ...
ensure
    # This gets executed no matter what
end

Now that you know how to handle errors, how do you go about raising
errors of your own? With raise, of course!

def mymethod data
    if data.is_malformed?
        raise ArgumentError
    end
end

Why would you want to do this? It can serve as a better reminder to
you or other programmers using your code that what they were doing is
wrong. This can help stop bugs.

This brings us to the end of the episode.

If you have any questions, comments, or suggestions about anything
related to Man With Code or these video tutorials; Please leave a
comment below, or email me at tyler@manwithcode.com

Do not forget to donate. A lot of time and hard work went into making
these. If you liked these videos the best way to show your
appreciation is by donating.

Thanks for watching, goodbye!

Programming With Ruby Episode 14, YAML

Covered in this Episode:

  • What is YAML
  • Why should you use YAML?
  • Storing Data

Transcript:

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

I will start off this episode telling you what YAML is and why you
should be using it. I will then be showing you how you can store
objects and various assorted other kinds of data using YAML.

Without further delay, lets get started!

What is YAML?

YAML stands for YAML Ain’t Markup Language. In the most basic sense it
is a way of storing data for later use.

Why should you use YAML?

Lets say you are writing a game, you could save your players progress
to a YAML file. Or if your writing an application with many preference
settings, you might save the user’s preferences to a YAML file.

Using YAML instead of creating your own text-based format creates more
portability, because other applications can immediately use your YAML
file instead of having to write their own custom file loader.

YAML also makes editing files by hand very easy to do if you have to.

Enough of all the theoretical talk, lets write some code!

Storing Data

Lets say we are writing a text editor and there are a few preferences the
user can change. We want the user to be able to set their preferences and
have them saved, so the next time they start up our text editor the
preferences are set the same as they were at last use.

We decide to use YAML to store our users preferences. Lets say for
example that the preferences are stored in a hash:

@preferences = {"word-wrapping" => true, "font-size" => 20, "font" => "Arial"}

To save that using YAML we have to use:

require 'yaml'

Open a file for writing (YAML files end in .yml or .yaml):

output = File.new('prefs.yml', 'w')

Use the YAML.dump method to get the text that will be outputted:

output.puts YAML.dump(@preferences)
output.close

Full source:

require 'yaml'
@preferences = {"word-wrapping" => true, "font-size" => 20, "font" => "Arial"}

output = File.new('prefs.yml', 'w')
output.puts YAML.dump(@preferences)
output.close

And that is how easy it is to store data!

We read back a file in a similar way, using the YAML.load method:

require 'yaml'

output = File.new('prefs.yml', 'r')
@preferences = YAML.load(output.read)
output.close

Don’t think you’re limited to simple data like hashes and arrays, you
can store objects too!

It has been my experience that it is usually best to store data in
hashes, because they automatically have a label, unlike an array. You
can do whatever you want to, but that is my recommendation.

Now comes the sad time when we have to close the episode.

Please don’t forget to donate, a few dollars can go a long way.

If you have any questions, comments or suggestions, please do not
hesitate to leave a comment below or email me at tyler@manwithcode.com

Thank for watching!

Bye!

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.