Programming With Ruby Episode 18, Out Into The World

Covered In This Episode:

  • Where to go from here
  • Books
  • Libraries
  • A few other things…

Transcript:

Hello Everybody and welcome to Programming With Ruby Episode 18, Out
Into The World. I’m Tyler and this video is brought to you by
manwithcode.com.

In this episode I will be telling you where to go from here, now that
you know the basics of Ruby. I’ll show you some books, some common
libraries. And I’ll go over a few more things.

Where to go from here

Now that this series is almost done, you may be wondering what you
should do. First, I recommend you start writing your own
programs. Find something you would like to write and just try writing
it.

You may also want to read a few other resources like books and online
tutorials about Ruby for things I didn’t cover and to reinforce what
you have learned.

For books I would recommend:

  • Beginning Ruby, From Novice to Professional
  • The Ruby Programming Language

If you are trying to make something, but can’t do it with Ruby alone,
here are some libraries in a few common areas. I won’t be providing
links, but a quick Google search will find them for you.

Web Development

  • Ruby on Rails
  • Sinatra
  • Merb

Game Development

  • Rubygame
  • rubysdl
  • Gosu

Testing

  • rspec
  • cucumber

Images

  • RMagic

GUI Toolkits

  • Ruby-WxWidgets
  • Ruby-GNOME2
  • Shoes

If you need a library for something I didn’t cover, you can check
Ruby’s documentation at ruby-doc.org, you can try and find a project
by searching at rubyforge.org and github.com. If all else fails, just
Google it.

This is actually the end of the episode, but though this video is
purported as the end of the series, there is going to be at least one
more video, so stay tuned.

If you’ve liked this series, please donate!

If you have and questions, comments, or suggestions about this series
or Man With Code, you can leave a comment on this page or email me at
tyler@manwithcode.com

Thanks for watching, goodbye!

Programming With Ruby Episode 17, Getting Advanced

Covered In This Episode:

  • Symbols
  • eval
  • Bindings
  • Running Other Programs
  • Safe Levels

Transcript:

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

By now, you know a large amount about Ruby, so in this episode we will
be going over some advanced features that Ruby has.

More specifically I will be teaching you what Symbols are, and when to
use them. I will be showing you how to use eval, and how to use
bindings with eval. You will learn how to run other programs from
Ruby. Finally I will show you what safe levels are.

Lets get started!

Symbols

Symbols are a type of variable that are very much like strings, but
more lightweight. Symbols look like this:

:variable

Symbols can’t be manipulated like strings can, which seems like a huge
drawback, but they do have a couple benefits.

Each time you use a string, to say access a hash. Ruby creates an
instance of that string. Where if you use a symbol, it is only ever
instanced once. Meaning that the use of symbols will take up less
memory than strings will, if you are, say accessing a hash many times.

Symbols are also slightly easier to type since the colon is on the
home row on US keyboards.

eval

eval is a way of running Ruby code that is contained in a string. For
example, lets say you have a string that looks like this:

"puts 'Hello World'"

It is just a simple string, so it does nothing. But, if you use the
method eval on that string it will execute the code inside. So this
will print Hello World! on to the screen:

eval "puts 'Hello World!'"

This isn’t always useful, but you can use it if you want your users to
be able to enter Ruby code into your program.

You can also pass bindings to eval. So if we had this method

def my_method my_binding
    eval "puts x", my_binding
end

x = 5
my_method binding

This outputs:

5

Some of you may notice that the variable x isn’t defined in the method my_method. By using the binding method, we can make variable scopes portable!

Running Other Programs

There comes a time when you will want to be able to run a program from
Ruby, maybe you want to automate something, or simply get the output
from an external program.

There are a few ways of doing this.

The first is with the method exec, which runs an external programs,
and quits the Ruby script at the same time:

exec('ls') # dir on windows
# Program never gets here

There is also system, which does the same thing, but doesn’t quit the
Ruby script, and returns true or false if the program was successful:

system('ls') # dir on windows
# we do get this far

Finally we have the “back-tick” `. Which looks like a sideways single
quote. On my keyboard it is above the tab key. You surround your
command in the back-ticks, like you would for a sting. Unlike the other
two methods of running a program, this method also returns the output
of the program you run.

variable = `ls`

Safe Levels

If you are running a Ruby interpreter online or in another environment
where users can enter in and run Ruby code. They hold the ability to
wreak havoc on your system.

The way to prevent this from happening is by using safe levels. Safe
levels are a way of preventing the user from getting access to the
file system, or changing any variables that the program has.

You set safe levels by setting the $SAFE variable. By default it is
set to zero.

$SAFE = 4

Ruby “taints” objects that could be dangerous.

There are five different safe levels.
0 => The default, you can do anything
1 => Can’t use environment variable, eval, load, require, and more.
2 => Same as above and also can’t use files
3 => All objects created are tainted, can’t be untainted
4 => You can do almost nothing… Can’t modify the untainted, can’t
use exit. Basically completely safe and sand-boxed.

That brings us to the end of the episode. If you liked these videos,
please donate. It costs me in both money and time to make them.

If you have any questions, comments, or suggestions please don’t
hesitate to leave a comment on this page or email me at
tyler@manwithcode.com

Thanks for watching, goodbye!

Programming With Ruby Episode 16, Benchmarking

Covered In This Episode:

  • What is benchmarking?
  • Benchmarking
  • Profiling

Transcript:

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

In this episode I will tell you what benchmarking is. You will learn
how to preform benchmarking tests on some of your code. And after that
you will learn how to preform the more exhaustive benchmarking process
called profiling.

This should be a very quick and easy episode, so lets get started!

What is benchmarking?

Basically benchmarking is measuring how fast your code runs. Whether
that means your code as a whole or only parts of it. This can be
useful so you can optimize your code to run faster, in the places it
is running the slowest. Benchmarking is also commonly used to compare
two different programs in the category of speed, which can be a
selling point for many products.

Benchmarking

To get access to benchmarking make sure you put:

require 'benchmark'

in your code.

The most simple form of benchmarking is Benchmark.measure:

a = Benchmark.measure do
    1_000_000.times do |i|
        x = i
    end
end

puts a #=> 0.400000   0.140000   0.540000 (  0.537934)

The last number is the actual time it took to run the test.

There is also Benchmark.bm, which is similar, but adds headings and
allows you to do multiple tests.

Benchmark.bm do |bm|
    bm.report('Test 1:') do
        1_000_000.times do
            x = 1
        end
    end
    bm.report('Test 2:') do
        1_000.times do
            x = "Moo..."
        end
    end
end

# Example Output:
#          user     system      total        real
# Test 1:  0.430000   0.120000   0.550000 (  0.563787)
# Test 2:  0.000000   0.000000   0.000000 (  0.000775)

Then there is Benchmark.bmbm, which is exactly the same as bm, but
preforms a benchmark twice.

Example Benchmark.bmbm Output:
Rehearsal -------------------------------------------
Test 1:   0.370000   0.110000   0.480000 (  0.484865)
Test 2:   0.000000   0.000000   0.000000 (  0.000529)
---------------------------------- total: 0.480000sec

user     system      total        real
Test 1:   0.390000   0.090000   0.480000 (  0.477402)
Test 2:   0.000000   0.000000   0.000000 (  0.000529)

And that is all there is to know about simple benchmarking, on to
profiling.

Profiling

Profiling takes benchmarking to the extreme. It tells you how much time each part of your code is take, and all you have to do is put:

require 'profile'

at the top of your program!

require 'profile'

class MyMath
    # Don't worry about the math, just the profiling output
    # We repeat the code to make it use up more time
    def self.x_offset angle, distance
        1000.times { distance * Math.sin(angle * Math::PI/180) }
    end

    def self.y_offset angle, distance
        1000.times { distance * Math.cos(angle * Math::PI/180) * -1 }
    end
end

MyMath.x_offset(220, 50)
MyMath.y_offset(220, 50)

And from the profiling output, we can see what took the longest:

%   cumulative   self              self     total
time   seconds   seconds    calls  ms/call  ms/call  name
72.41     0.21      0.21        2   105.00   145.00  Integer#times
10.34     0.24      0.03     4000     0.01     0.01  Fixnum#*
6.90     0.26      0.02     1000     0.02     0.02  Math.cos
6.90     0.28      0.02     2000     0.01     0.01  Float#/
3.45     0.29      0.01     1000     0.01     0.01  Float#*
0.00     0.29      0.00        1     0.00   140.00  MyMath#y_offset
0.00     0.29      0.00        1     0.00   150.00  MyMath#x_offset
0.00     0.29      0.00        1     0.00     0.00  Class#inherited
0.00     0.29      0.00     1000     0.00     0.00  Math.sin
0.00     0.29      0.00        2     0.00     0.00  Kernel.singleton_method_added
0.00     0.29      0.00        1     0.00   290.00  #toplevel

And that is it for today’s episode!

Please do not forget to show your appreciation by donating.

If you have any thing to say about anything related to Man With Code
or these videos, please leave a comment below, or email me at
tyler@manwithcode.com

Thanks for watching, Bye!

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!