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 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 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!