Man With Code 👨‍💻

In which I occasionally teach you things.

Category: Videos

What is TypeScript?

Series: Learn TypeScript

Transcript:

So what is TypeScript?

At a super high level TypeScript is JavaScript with static type checking. What that really means is that you no longer have to write JavaScript code purely based on faith and good guesses that the variables and objects you're using are what you think they are.

TypeScript is going to come along side you and enforce that "hey this is a string this is a number this is you know some object with a certain felds" TypeScript is going to add those guarantees so that you can code with more confidence.

In practice you'll find that you'll have fewer dumb errors; If you're working on a team, it becomes vastly easier to communicate what certain code does because they can see right there what the types are and when they go to use them TypeScript is going to tell them if they're using them erroneously.

It is easier to communicate with your future self so that when you come back to your code it's easier to tell how things work. You can just look and see what the types of various objects are without having to go back and actually run the program to see if the guesses you're making about the program are actually true.

In short, the code has become much more self-documenting

If you go to the TypeScript website you'll see Microsoft describes TypeScript as "JavaScript that scales". What does that really mean?

What it has meant in my experience is that you can bring a team of people together or you can work on something yourself and you can build programs and applications that very large and complex and you'll going to have much more confidence in what your building and in and how you're managing the complexity then you would be if it was just plain JavaScript.

I can recall numerous times on plain JavaScript projects before we started using TypeScript that I would go to refactor something or move some code around or change some logic or whatever and I could never be entirely sure that I hadn't broken something. Even if my tests pass even if in my manual testing everything was working right, I was never able to be fully confident in the changes I had made. It seems like there would always be something flew under the radar that got missed.With TypeScript that happens far far less often, in fact I'd say almost never.

TypeScript is a strict superset of JavaScript. What that means is that anything you know about JavaScript you can transfer into your knowledge of TypeScript. There are definitely new things to learn, but it's not a whole new world that you'll be completely lost and confused in. If you already know JavaScript, you'll be good to go.

In a lot of cases you can take code that you've already written in JavaScript change the file extension from .js to .ts and everything will work, or most of it will work with maybe a few extra type annotations that you need to add in. So it's very straightforward to get started and to jump in.

Another great thing about TypeScript is that it compiles directly to JavaScript. In practice that means that you don't have to install any extra runtime or ship any additional library to your users in order to start using TypeScript in your application. In development, you'll just run the TypeScript compiler and then away you go.

Since it's just plain JavaScript you can use the same debugging tools that you're already used to. You can also graudually introduce TypeScript into an existing JavaScript project, slowly converting files to TypeScript bit by bit as you go along.

If you've used other languages that compile to JavaScript, you might be used to the compiled code looking unintelligible, very much like a machine wrote it. In most caess, TypeScript is merely erasing your type annotations, so your original code remains. In cases where it does have to manipulate things, I've found it makes very readable choices about the code it produces.

Anothing great thing about TypeScript too is that it supports many of the new features that have been added to JavaScript in ES6 and other newer JavaScript versions. Not only that, but you can have TypeScript compile to older JavaScript versions so that you can use the latest features in TypeScript, but still support older browsers.

One thing I wanted to mention as well is that the types are in a lot of cases optional, or what you might call a gradual, or can be inferred by TypeScript. That means there's a lot of cases where you don't really need to tell it what the type of something is, it'll see "hey I'm setting this variable to a string so that must be a string", and you don't have to do the redundant typings that you might have gotten used to if you came from a C# for a Java background, and that's really nice.

Also, depending on the configuration flags you set and how much you use the catch-all "any" type, you can use the type checking as much or as little as you want. If you want it to be super strict and have types everywhere, you can, or if you want to write JavaScript in the more dynamic untyped way that you're used to, you totally can.

I think TypeScript helps enforce some good habits in a few different ways. First, once you get used to the typings, it becomes very natural when writing new code to sketch out the interfaces and relationships between data before you start writing code, because you can use those right away when you start actually implementing your program, rather than just leaving them as inert comments or notes or thoughts in your head.

Second, depending on how you configure TypeScript you can make it so it's much more strict about checking for null and undefined, which is a really good habit to get into.I've been guilty myself of getting lazy and thinking "well this could fail as null or undefined, but I'm just going to ignore it because it makes my code a lot simpler." But if TypeScript is yelling at me I'm much more likely to do the proper thing and that's really good.

Third, if you're defining a type and it becomes hard to think about or it hard to describe a lot of times that's been an indication to me that "hey I'm making this more complicated than it needs to be" or I'm I'm trying to do this in a way that might be clever now but it isn't going to stand up to the test of time. I'm going to come back to this later be super confused or I'm going to have to hand this off to a co-worker and they're going to be super confused.

Better IDE support is one thing that's great is if you're using something like Visual Studio Code or JetBrains WebStorm or any other IDE or Smart Text Editor with TypeScript. You get way better auto completion so you can access things or call functions and it's going to tell you "hey this is how you call this thing" or "hey that's an error you missed a parameter here" and that kind of thing.

If you've used just plain JavaScript in the past, you'll know that IDEs can be pretty good about guessing what things might be, but there's a lot of times where you'll start typing a piece of code and it does the auto-completion and gives you every possible field name that I've defined in my project as an option. Which is massively unhelpful. With TypeScript you avoid that issue entirely, since it knows what the types of things are, you get vastly better auto completion support. Which makes you a much happier and more productive programmer.

So that's a general overview of what TypeScript is. I hope that was helpful to you! I've got other videos out there on TypeScript, so if you want to learn more, please check them out!

If you visit https://typescriptbyexample.com you'll see some info on a course that I'm building for TypeScript. You can put your email address in at the bottom of the page and you'll be notified when that's ready. I'd love to hear from you, and I'd love to have you be a part of the course. Thank you so much for watching! Goodbye!

Keep reading...

How to Install TypeScript on Linux

Series: Learn TypeScript

Transcript:

Alright! Hello everybody! So, I wanted to show you how to install TypeScript on Linux. Before we get started, a word of caution. Every Linux distribution is a little bit different, in theory everything I show you here should work across most distributions, but it's possible that yours might do something a little different. For reference, I'm using Ubuntu 18.04.1 LTS release for this video.

One thing I want to point out before I get started is that most Linux distributions have some sort of package management system that you may be able to use to install TypeScript. For example, Ubuntu offers the node-typescript package, which you can install via apt.

The problem is that these package managers often contain old versions of TypeScript, and TypeScript releases quite frequently, so today I'm going to be showing you how to install TypeScript directly from the source so you can be running the latest and greatest version.

So, to get started we're going to open up whatever your favorite browser is, or whatever browser you have installed. Here I'm going to be using Firefox.

We are going to head over to https://nodejs.org Now, you'll see a page like this. It'll give you a couple of different download options and you can opt for either the LTS or the current release.

Either one of those works. I'm going to say go for the LTS version. That's because that stands for long-term support, so this is the version that's going to keep getting security updates and things like that.

That's probably the one you'll want to go with. If you want to be on the bleeding edge, and have the latest and greatest feel free to go with the other one, it will work just as well.

For this video I'm going to go with 10.15.1. Very likely if you're watching this at any point in the future these version numbers are going to be different. Node.js does a lot of releases so, it's totally okay if you're on a later version than I am. Everything should work just as well.

Download it.

Alright, it has finished downloading, so let's open a Terminal and extract the files and get started.

Here I've opened the default Terminal that comes with Ubuntu. We're going to do:

cd Downloads

to get to our downloads folder.

We're then going to type:

tar xvf node-v10.15.1-linux-x64.tar.xz

Hit enter. It'll print out the files it unzipped and then we should be able to see the new folder.

Next we need to add Node.js to our PATH. We can do this by typing:

export PATH=~/Downloads/node-v10.15.1-linux-x64/bin:$PATH

Now that Node.js is on our PATH, we can test if Node.js is installed properly by typing:

node

and hitting enter.

And this little angle bracket should appear. And we can start entering JavaScript code here.

So, two plus two is four. Let's see, we could do a setTimeout. So in 5 seconds that should display something. There it is.

If you want to get out of here just hit CTRL+C. Twice. And then you're back on the normal Terminal prompt.

In order to use Node.js and TypeScript in future Terminal sessions, we'll need to put that PATH line at the end of your .bashrc or .bash_profile file, or whatever profile file your shell of choice uses if you're not on bash. To do that I'm going to open up Ubuntu's default text editor.

We'll hit open, and navigate to our home directory. Note that you'll need to ensure that hidden files are showing. I can do that here by pressing CTRL+H. I'll open .bashrc, copy that line from before, paste it to the bottom, and then save the file. And then, hey presto, any subsequent Terminals we open will have Node.js available to us.

So, all that out of the way, let's install TypeScript! In order to install TypeScript we're going to use something called npm. If you're unfamiliar with npm that stands for the node package manager and that's how lots of different Node.js based libraries and programs are distributed, TypeScript among them.

How do we use npm to install it? Well, here in this Terminal we're going to type:

npm install --global typescript

And hit enter.

Note that if you've installed Node.js and npm from your package manager, you may need to prefix the previous command with sudo to run it with root priviledges

And you'll see here it says added one package from one contributor in 1 second.

Now it's very likely that you'll see a different version number here. TypeScript also like Node.js releases fairly frequently. TypeScript is really good about backwards compatibility, so you shouldn't have to worry about anything you see in this video or any later video being incompatible.

If you wanted to be on the exact version that I am going to show you, though, what you can do is go back to the Terminal and run:

npm uninstall --global typescript

to get rid of what we just installed.

And we'll then run a command similar to what we did before:

npm install --global [email protected]

When you add that @ sign and then the version number, it's going to guarantee that that's the version you're going to install rather than whatever the latest is (which is the default).

There we go. We've got that working.

So now what I'm going to do is create a new folder on the desktop. We're going to call it "test" and we're just going to see if TypeScript is working.

Let's open up "test".

We're going navigate our Terminal to this new folder as well. You can do this by typing:

cd ~/Desktop/test

Once you've done that we're going to create a file named main.ts. All TypeScript files end in .ts.

You can do this by entering the comand:

touch main.ts

You'll see the file appears in the folder.

Now let's put something in this main.ts file for TypeScript to compile. So, we're going to open up the default text editor that comes with Ubuntu. If you have a particular text editor that you prefer, feel free to use it.

I'm going to go to Open and find main.ts in the folder on my Desktop.

And then we'll put in the simplest possible "Hello, World!" program and save it.

console.log("Hello, World!");

Now in order for TypeScript to compile our "Hello, World!" program it needs a configuration file.

We can create the default one by going back to our Terminal and running:

 tsc --init

When we hit enter, it's going to create that file for us. So, you can see this tsconfig.json file has been created.

Don't worry too much about that file I will be creating a video explaining exactly what it is, why we use it, how to use it, what the different options inside it mean for now all we need to know is that we need it there and now we have it.

And to get TypeScript to compile our main.ts file, just run:

tsc

and hit enter. It will find all the TypeScript files in this folder and compile them. You see we now have a main.js file.

We'll run that main.js file through Node.js:

node main.js

And see we've got "Hello, world!"

Awesome! Exactly what we wanted.

So everything's working. If you're seeing the same thing, hey you're good to go, you've got TypeScript installed.

There is one other thing I wanted to show you: You can have TypeScript watch for changes, rather than having to rerun it each time you change something. So, what we're going to do is do is go back to our Terminal and enter:

tsc --watch

See it gives us a little message "starting compilation in watch mode".

And then I'm going to go back to our file and say "Hello World! Again!" and I'm going to save it. And you see that flashed a bit. It said "file change detected", "0 errors".

We're going to open up another Terminal and do the same:

cd ~/Desktop/test"

that we did before.

You can see if we run our main.js, hey! It says "Hello World! Again!" just like we wanted.

One thing that's really nice about this is that if you make a mistake, here I'm going to forget to have the closing parenthesis and semicolon, if we save this TypeScript is going to give us an error and say "hey! I expected a closing parenthesis here!"

So we can add that back in and save it and everything's happy again.

Very cool! That's it! You've got TypeScript installed!

By the way if you're interested in going deep into learning TypeScript I've got this TypeScript by Example course that I'm working on now. You can head on over to https://typescriptbyexample.com Scroll down to the bottom, and you can put in your email address to be notified when the course is released. Also, stay tuned to this YouTube channel for future updates. Thank you so much for watching!

Keep reading...

How to Install TypeScript on macOS

Series: Learn TypeScript

Transcript:

Alright! Hello everybody!

So, I wanted to show you how to install TypeScript on macOS.

So, first things first we're going to open up whatever your favorite browser is, or whatever browser you have installed. Here I'm going to be using Safari.

We are going to head over to https://nodejs.org

Now, you'll see a page like this. It'll give you a couple of different download options and you can opt for either the LTS or the current release.

Either one of those works. I'm going to say go for the LTS version. That's because that stands for long-term support, so this is the version that's going to keep getting security updates and things like that.

That's probably the one you want to go with.

If you want to be on the bleeding edge, and have the latest and greatest feel free to go with the other one, it will work just as well. For this video I'm going to go with 10.15.1.

Very likely if you're watching this at any point in the future these version numbers are going to be different. Node.js does a lot of releases so, it's totally okay if you're on a later version than I am. Everything should work just as well.

Download it.

Alright, it has finished downloading, so I'm going to go to my Downloads folder and open it.

We're just going to click through here.

We'll hit continue.

We'll hit continue again. It'll prompt us to agree to the license, click agree.

It'll take 60 megabtyes of space, that's fine by me, hit Install.

Enter your account password at the authorization prompt and hit Install Software.

Give that a few moments. Alright, and Node.js has been installed! Hit Close.

We don't need the installer any more, so just hit "Move to Trash" here.

So, how can we verify that things are working here?

Well, let's go to the application search in the top-right corner of the screen and look for "Terminal".

Here we've got our Terminal. The way we can test if Node.js is installed properly is to type:

node

and hit enter.

And this little angle bracket should appear.

And we can start entering JavaScript code here. So, two plus two is four. Let's see, we could do a setTimeout. So in 5 seconds that should display something. There it is.

If you want to get out of here just hit CTRL+C. Twice.

And then you're back on the normal Terminal prompt.

So, let's install TypeScript.

In order to install TypeScript we're going to use something called npm. If you're unfamiliar with npm that stands for the node package manager and that's how lots of different Node.js based libraries and programs are distributed, TypeScript among them.

So, how do we use npm to install it? Well, here in this Terminal we're going to type:

sudo npm install --global typescript

And hit enter.

Enter our password. Give that a few moments to do its thing.

And you'll see here it says added one package from one contributor in 6 seconds.

Now it's very likely that you'll see a different version number here. TypeScript also like Node.js releases fairly frequently. TypeScript is really good about backwards compatibility, so you shouldn't have to worry about anything you see in this video or any later video being incompatible.

If you wanted to be on the exact version that I am going to show you, though, what you can do is go back to the Terminal and run:

sudo npm uninstall --global typescript

To get rid of what we just installed. And we'll then run a command similar to what we did before:

sudo npm install --global [email protected]

When you add that @ sign and then the version number, it's going to guarantee that that's the version you're going to install rather than whatever the latest is (which is the default).

There we go. We've got that working.

So now what I'm going to do is create a new folder on the desktop. We're going to call it "test" and we're just going to see if TypeScript is working. It's installed but is it actually working?

Let's open up "test". We're going navigate our Terminal to this new folder as well. You can do this by typing:

cd Desktop/test

Once you've done that we're going to create a file named main.ts. All TypeScript files end in .ts.

You can do this by entering the comand:

touch main.ts

You'll see the file appears in the folder.

Now let's put something in this main.ts file for TypeScript to compile.

So, we're going to open up TextEdit. If you have a particular text editor that you prefer, feel free to use it. TextEdit is all I've got on this particular machine at the moment. I'm going to go to File -> Open and find main.ts in the folder on my Desktop.

And then we'll put in the simplest possible "Hello, World!" program and save it.

Now in order for TypeScript to compile our "Hello, World!" program it needs a configuration file.

We can create the default one by going back to our Terminal and running:

tsc --init

If we hit enter, it's going to create that file for us. So, you can see this tsconfig.json file has been created.

Don't worry too much about that file I will be creating a video explaining exactly what it is, why we use it, how to use it, what the different options inside it mean for now all we need to know is that we need it there and now we have it.

And to get TypeScript to compile our main.ts file, just run:

tsc

It will find all the TypeScript files in this folder and compile them. You see we now have a main.js file.

We run that main.js file through Node.js, and see we've got "Hello, world!"

Awesome! Exactly what we wanted.

So everything's working. If you're seeing the same thing, hey you're good to go, you've got TypeScript installed.

There is one other thing I wanted to show you: You can have TypeScript watch for changes, rather than having to rerun it each time you change something.

So, what we're going to do is do is go back to our Terminal and enter:

tsc --watch

See it gives us a little message "starting compilation in watch mode".

And then I'm going to go back to our file and say "Hello World! Again!" and I'm going to save it. And you see that flashed a bit. It said "file change detected", "0 errors".

We're going to open up another Terminal and do the same "cd Desktop/test" that we did before.

You can see if we run our main.js, hey it says "Hello World! Again!" just like we wanted.

One thing that's really nice about this is that if you make a mistake, here I'm going to forget to have the closing parenthesis and semicolon, if we save this TypeScript is going to give us an error and say "hey! I expected a closing parenthesis here!"

So we can add that back in and save it and everything's happy again.

Very cool! That's it!

You've got TypeScript installed!

By the way if you're interested in going deep into learning TypeScript I've got this TypeScript by Example course that I'm working on now.
You can head on over to https://typescriptbyexample.com

Scroll down to the bottom, and you can put in your email address to be notified when the course is released.

Also, stay tuned to this YouTube channel for future updates. Thank you so much for watching!

Keep reading...

How to Install TypeScript on Windows

Series: Learn TypeScript

Transcript: Alright! Hello everybody! So, I wanted to show you how to install TypeScript. So, first things first we're going to open up whatever your favorite browser is, or whatever browser you have installed. We are going to head over to nodejs.org. Now, you'll see a page like this. It'll give you a couple of different download options and you can opt for either the LTS or the current release. Either one of those works. I'm going to say go for the LTS version. That's because that stands for long-term support, so this is the version that's going to keep getting security updates and things like that. That's probably the one you want to go with. If you want to be on the bleeding edge, and have the latest and greatest feel free to go with the other one, it will work just as well. For this video I'm going to go with 10.15.1. Very likely if you're watching this at any point in the future these version numbers are going to be different. Node.js does a lot of releases so, it's totally okay if you're on a later version than I am. Everything should work just as we;ll. Download it. Antivirus just finished scanning it, and here it is it's open. You might need to go find it in your downloads folder and double-click on it. I just had it run when I download it. We're just going to click through here. We're going to accept the license agreement. We're going to accept the default install path. We're going to leave all these things on the defaults. Install. We get our security prompt here will say yes so that it can install. Give that a few moments. Alright, and Node.js has been installed. So, how can we verify that things are working here? Well, let's go to the start menu there should be something called Node.js command prompt in there and Node.js itself in your start menu. You might have to search for it. Here it's showing up under my recently added. So if we go in here we have an Node.js command prompt. This looks very much like any other command prompt you may have seen. Just for comparison, Let's open up the other one. You can see normally for just a plain old command prompt we get the windows version information. But here we're actually getting the Node.js version information. So, we can tell that things are working already. The way you can test Node.js is type node and hit enter. And this little angle bracket should appear. And we can start entering JavaScript code here. So, two plus two is four. Let's see, we could do a setTimeout. So in 5 seconds that should display something. There it is. If you want to get out of here just hit CTRL+C. Twice. And then you're back on the normal command prompt. So, let's. install TypeScript. So, alright so to install TypeScript we're going to use something called npm. If you're unfamiliar with npm that stands for the node package manager and that's how lots of different Node.js based libraries and programs are distributed, TypeScript among them. So TypeScript is written in JavaScript and it is distributed Via npm because it runs on Node.js. So, how do we use npm to install it? Well, here in this Node.js Command Prompt we're going to type npm install --global typescript . Going to hit enter. Give that a few moments to do its thing. And you'll see here it says added one package from one contributor in one second. Now it's very likely that you'll see a different version number here. TypeScript also like Node.js releases fairly frequently. TypeScript is really good about backwards compatibility, so you shouldn't have to worry about anything you see in this video or any later video being incompatible. If you wanted to be on the exact version that I am going to show you, though, what you can do is we're going to do:
npm uninstall --global typescript
And similar to before we're going to do:
npm install [email protected]
and so if you add that @ sign and then the version number, that's going to guarantee that that's the version you're going to install rather than whatever the latest is which is the default. There we go. We've got that working. So now what I'm going to do is create a new folder on the desktop. We'going to call it "test" and we're just going to see if TypeScript is working. It's installed but is it actually working? We're going to open up "test". We're going to create a new file. We're going to call this main.ts. All TypeScript files end in .ts So, if you do what I did there and go to "New Text Document" it might not let you edit the file extension depending on what you're doing, and you could end up with something that's actually.ts.txt, which really isn't what you want. The way you can check for this is you can go to this View tab that's up here and make sure this "file name extensions" checkbox is checked. You can see if I uncheck it the file extension goes away, and you can't tell what it is. If I check it it tells me we've got main.ts which is what we want. So we're going to move our Command Prompt into this folder. How do you do that? I'm going to click here to get the full path to this folder. Then type cd which stands for "change directory" and do a quote. If you right click it's going to paste what you just copied. We're going to do an end quote. And here we are in that folder. Now in order for TypeScript to compile something it needs a configuration file. We can create the default one by running:
tsc --init
If we hit enter, it's going to create that file for us. So, you can see this tsconfig.json file has been created. Don't worry too much about that file I will be creating a video explaining exactly what it is. Why we use it, how to use it, what the different options inside it mean for now all we need to know is that we need it there and now we have it. Now before we go compiling anything with TypeScript we should probably put something in this main.ts file for TypeScript to compile. So, we're going to open up notepad. Feel free to use any other text editor of your choice. That's just all I've got on this particular machine at the moment. And we're going to go in, and I'm going to switch this over to "all files" so I can see my main.ts and we're just going to write a super simple "Hello, world!" program. There you go, there's your "hello world". Hit CTRL+S to save it. Minimize that. And then to get TypeScript to compile your files. Just run tsc. It will find all the TypeScript files in the folder and compile them. You see we now have a main.js file. We run that made that main.js file through Node.js. And see we've got "Hello, world!" Awesome! Exactly what we wanted. So everything's working. If you're seeing the same thing, hey you're good to go, you've got TypeScript installed. One other thing I wanted to show you. Was that you can have TypeScript, rather than having to rerun it each time you change something, you can have TypeScript watch for changes. So, what we're going to do is do:
tsc --watch
We're going to hit enter. See it gives us a little message "starting compilation in watch mode". I'll move this so you can see it, and then I'm going to say "Hello World! Again!" and I'm going to hit CTRL+S to save right now. And you see that flashed a bit. It said "file change detected", "0 errors". We're going to open up another Node.js Command Prompt. Do the same thing we did before so we can run this. You can see if we run our main.js, hey it says hello world again just like we wanted. One thing that's really nice about this is that if you make a mistake, here I'm going to forget to have the closing parenthesis and semicolon, if we save this TypeScript is going to give us an error and say "hey! I expected a closing parenthesis here!" So we can add that back in and save it and everything's happy again. Very cool, you've got TypeScript installed! By the way if you're interested in going deep into learning TypeScript I've got this TypeScript by Example course that I'm working on now. You can head on over to typescriptbyexample.com. Scroll down to the bottom, and you can put in your email address to be notified when the course is released. Also, stay tuned to this YouTube channel for future updates. Thank you so much for watching!
Keep reading...

Making Games with Ruby Ep. 3 - Basics

Series: Making Games With Ruby

Covered In This Episode:
  • Creating a Window
  • Basic Event Handling
Transcript: Hello Everybody and welcome to making games with Ruby episode 3, Basics. I'm Tyler and these videos are brought to you by manwithcode.com. Today we're just going to be talking about the very basics of game creation, just getting a window on the screen. The code for this episode is on manwithcode.com, if you're not there already. http://manwithcode.com/322/making-games-with-ruby-ep-3-basics Lets get started! We're going to start by requiring in the libraries we need, which for now is only rubygems and rubygame: [source lang="ruby"] require 'rubygems' require 'rubygame' [/source] Then we're going to create the main Game class, and stub out all the methods in it: [source lang="ruby"] class Game def initialize end def run! end def update end def draw end end [/source] And after that we're going to add the code to run the game: [source lang="ruby"] g = Game.new g.run! [/source] So far this is just some very basic structure, nothing really happens yet. I'm going to run the code just to double check we have no syntax errors... The first thing we're going to do is initialize everything we'll need: [source lang="ruby"] def initialize @screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF] @screen.title = "Pong" @queue = Rubygame::EventQueue.new @clock = Rubygame::Clock.new @clock.target_framerate = 60 end [/source] Some of this is self explaitory, but let's break it down. The first line of initialize creates the window for our game, Rubygame calls this a Screen. The first argument [640, 480] is the size of the screen, the second is the screen depth (you don't need to worry about this), the last one is a list of flags we pass to rubygame. HWSURFACE means we want it to be accelerated on the graphics card if available, and DOUBLEBUF means we want the screen to be double buffered. Double buffering is a way of drawing to the screen. I won't go into too much detail right now to explain double buffering, but I will in a later episode. The second line has an obvious purpose, it sets the title at the top of the screen to Pong The fifth line is setup so we can handle events, I'll talk more about this later. The last two lines are the setup so we can limit the framerate to 60 frames per second. The frame rate is how many times the screen is drawn every second (we'll be doing our drawing in the Game#draw method). If we let this go unchecked, our game will run as fast as possible which isn't desireable since top speed will be different on different computers, and depending on what the game is doing at a particular moment in time. I think 60 is a good number, but we can easily change it later if we want. Next we're going to setup the main game loop: [source lang="ruby"] def run! loop do update draw @clock.tick end end [/source] This loops indefinately until we decide in a different part of the code to end the game. @clock.tick is what allows us to limit our framerate. You can now run the game, it should just be a black screen. You can see the title at the top, like we set in the initialize function. But if you try to close the window... Nothing happens!!! To close it try pressing CTRL+C in the command prompt window, or you may have to go to the task manager and kill it from there. To fix this problem, we need to talk about the event queue. We're going to start by defining the update method: [source lang="ruby"] def update @queue.each do |ev| case ev when Rubygame::QuitEvent Rubygame.quit exit end end end [/source] Whenever the user gives us some input, presses a key, moves the mouse, etc. the Rubygame adds an event for this input onto the queue. We handle these events in our update method. @queue.each loops over each event, and we have a case statement that handles the event depending on the type. For closing the window, the event type is Rubygame::QuitEvent, which is generated whenever the user presses the close window button or ALT+F4. Now if you run the game, the window should appear and you should be able to close it now! Yay! This is the final source listing for this episode: [source lang="ruby"] require 'rubygems' require 'rubygame' class Game def initialize @screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF] @screen.title = "Pong" @queue = Rubygame::EventQueue.new @clock = Rubygame::Clock.new @clock.target_framerate = 60 end def run! loop do update draw @clock.tick end end def update @queue.each do |ev| case ev when Rubygame::QuitEvent Rubygame.quit exit end end end def draw end end g = Game.new g.run! [/source] This brings us to the end of the episode. If you have any questions, comments, or suggestions, leave a comment on this page or email me at [email protected]. Thank you very much for watching! Goodbye!
Keep reading...

Making Games with Ruby Ep. 2 - Setup

Series: Making Games With Ruby

Windows: [source language="plain"] gem install rubygame [/source] Mac: Linux: [source language="plain"] sudo apt-get install -y libsdl1.2debian libsdl1.2-dev libsdl-image1.2 libsdl-image1.2-dev libsdl-ttf2.0-0 libsdl-ttf2.0-dev libsdl-mixer1.2 libsdl-mixer1.2-dev libsdl-gfx1.2-4 libsdl-gfx1.2-dev sudo gem install rubygame [/source] Links: Covered in This Episode:
  • How to get set up for this series on Windows, Mac, and Linux
Keep reading...

Making Games With Ruby Ep. 1 - Intro

Series: Making Games With Ruby

Links: Covered In This Episode:
  • What you'll learn
  • What we're using
  • What I'm assuming about you
  • Why I'm teaching this
Transcript: Hello Everybody, and Welcome to the first episode of Making Games With Ruby! I'm Tyler, and this video is brought to you by manwithcode.com In this episode I'll be covering what you will be learning in this series, what we're using to develop our games, what I'm assuming about you, and why I'm teaching you. What you'll learn If you couldn't tell by the title, you're going to learn how to make games using the Ruby programming language. More specifically I'm going to teach you how to make Pong. Though Pong may sound a little simplistic, and I'm not claiming it isn't, learning how to make Pong will teach you almost everything you'll need to know to make any game, with out getting bogged down in game specific details. What we're using Of course we're using the Ruby programming language. To create games, we'll have the help of the Rubygame library, which is many things including a wrapper around SDL, and a nice framework for developing games. In the creation of this series I will be using Ruby 1.8.7-p174, and Rubygame 2.6.2. Theoretically The code in this series should run on Ruby 1.8.whatever and Rubygame 2.whatever, no promises though, since languages and libraries change. And if you want to know about my environment, I'll be running Ubuntu 9.10 as my Operating System, and using Gedit as my text editor. You can write and run the code on any platform you wish, but this is what I prefer. What I'm assuming about you So I don't have to explain every line of code to you, I'm going to be assuming that you already know the Ruby programming language. If you don't there are many books available, as well as my own video series Programming With Ruby at http://manwithcode.com/ruby-programming-tutorials/ Just reading one book, or watching my video series probably isn't enough. I'll be easier if you have used Ruby for a while, and are comfortable with it. This isn't a requirement, but it would help make things easier on yourself. Why I'm teaching this There are many reasons why, but I'll talk about the most important few: 1) I love making games. 2) I love teaching. 3) Teaching teaches me something. - When you actually sit down and think about what you do, things become more concrete, and you know why you do what you do, or even see bad habits that you need to correct 4) I'm trying to make money - Yep, I'm not going to try and hide this. Some of the videos in this series will be put up for sale, you'll be able to see them as I put out more videos. Thank you very much for watching! I'll see you in the next video.
Keep reading...

Programming With Ruby, Feedback

Series: Ruby Programming

Links: Covered In This Episode:
  • $1000 or 1000 comments
  • Submit to Social Media
Transcript: Hello Everybody and welcome to Programming With Ruby, Feedback. I'm Tyler, and this video is brought to you by manwithcode.com. In this video I'm going to be going over what needs to happen for me to produce the next series of video tutorials. All links I mention will be in the video description First things first, if you head on over to http://manwithcode.com/tutorials-under-consideration/ You can vote on what the next video series will be. So if you vote I will know what YOU want, now you need to know what I want for the next series to happen. I've had well over 1,000 unique viewers of this video series, so I need you viewers to donate a total of $1000 before I make the next series. This may seem like a high amount, but if only 200 people donate $5, that is a thousand dollars. Donate: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=4222118 Now, what if you don't have the money to donate? I will be making a post on manwithcode.com named Ruby Video Tutorial Feedback, if 1000 people leave feedback (i.e. What they liked, what they didn't like). So whatever comes first, 1000 comments or $1000 will cause me to start the next video series. For updates on how close we are to each goal, I will be on twitter at the account tylerjchurch and with the tag #manwithcode. Now what if you can't donate money, and you can't write me feedback? Then there is something else you can do! http://manwithcode.com/ruby-programming-tutorials/
  • Tweet on Twitter
  • Give a thumbs up on StumbleUpon
  • Submit to Digg
  • Submit to Reddit
  • Bookmark on delicious
  • Blog about
  • or you can just Tell a friend
And hopefully one of those people who come along will donate or leave feedback. So don't forget to donate, leave feedback, or submit the provided link to social media! Thanks for watching, bye!
Keep reading...

Programming With Ruby Episode 18, Out Into The World

Series: Ruby Programming

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 [email protected] Thanks for watching, goodbye!
Keep reading...

Programming With Ruby Episode 17, Getting Advanced

Series: Ruby Programming

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: [source language="ruby"] :variable [/source] 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: [source language="ruby"] "puts 'Hello World'" [/source] 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: [source language="ruby"] eval "puts 'Hello World!'" [/source] 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 [source language="ruby"] def my_method my_binding eval "puts x", my_binding end x = 5 my_method binding [/source] This outputs: [source] 5 [/source] 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: [source language="ruby"] exec('ls') # dir on windows # Program never gets here [/source] 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: [source language="ruby"] system('ls') # dir on windows # we do get this far [/source] 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. [source language="ruby"] variable = `ls` [/source] 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. [source language="ruby"] $SAFE = 4 [/source] 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 [email protected] Thanks for watching, goodbye!
Keep reading...

Programming With Ruby Episode 16, Benchmarking

Series: Ruby Programming

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: [ruby] require 'benchmark' [/ruby] in your code. The most simple form of benchmarking is Benchmark.measure: [ruby] a = Benchmark.measure do 1_000_000.times do |i| x = i end end puts a #=> 0.400000   0.140000   0.540000 (  0.537934) [/ruby] 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. [ruby] 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) [/ruby] Then there is Benchmark.bmbm, which is exactly the same as bm, but preforms a benchmark twice. [source] 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) [/source] 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: [ruby] require 'profile' [/ruby] at the top of your program! [ruby] 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) [/ruby] And from the profiling output, we can see what took the longest: [source] %   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 [/source] 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 [email protected] Thanks for watching, Bye!
Keep reading...

Programming With Ruby Episode 15, Error Handling

Series: Ruby Programming

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: [ruby] begin # Code here end [/ruby] 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. [ruby] begin # Possibly error inducing code here rescue # What to do if an error happens end [/ruby] 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: [ruby] begin # Possibly error inducing code rescue ArgumentError # If ArgumentError is raised rescue NoMethodError # If NoMethodError is raised end [/ruby] 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! [ruby] begin # ... rescue # ... ensure # This gets executed no matter what end [/ruby] Now that you know how to handle errors, how do you go about raising errors of your own? With raise, of course! [ruby] def mymethod data if data.is_malformed? raise ArgumentError end end [/ruby] 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 [email protected] 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!
Keep reading...

Programming With Ruby Episode 14, YAML

Series: Ruby Programming

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: [ruby] @preferences = {"word-wrapping" => true, "font-size" => 20, "font" => "Arial"} [/ruby] To save that using YAML we have to use: [ruby] require 'yaml' [/ruby] Open a file for writing (YAML files end in .yml or .yaml): [ruby] output = File.new('prefs.yml', 'w') [/ruby] Use the YAML.dump method to get the text that will be outputted: [ruby] output.puts YAML.dump(@preferences) output.close [/ruby] Full source: [ruby] require 'yaml' @preferences = {"word-wrapping" => true, "font-size" => 20, "font" => "Arial"} output = File.new('prefs.yml', 'w') output.puts YAML.dump(@preferences) output.close [/ruby] And that is how easy it is to store data! We read back a file in a similar way, using the YAML.load method: [ruby] require 'yaml' output = File.new('prefs.yml', 'r') @preferences = YAML.load(output.read) output.close [/ruby] 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 [email protected] Thank for watching! Bye!
Keep reading...

Programming With Ruby Episode 13, Basic I/O

Series: Ruby Programming

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: [ruby] my_file = File.new('file', 'r') my_file.close [/ruby] 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! [ruby] my_file = File.new('example.txt', 'w') my_file.puts "Hello World!" my_file.close [/ruby] If you want to read from a file you can use File.read: [ruby] my_file = File.new('example.txt', 'r') puts my_file.read my_file.close [/ruby] 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?: [ruby] File.exists("notes.txt") [/ruby] 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. [ruby] File.open('hello.txt', 'w') do |file| file.puts "Hello World!" end [/ruby] 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: [ruby] Dir.mkdir("Hello") [/ruby] You can get an array of all the files and directories that are in the current directory with Dir.entries: [ruby] Dir.entries('.') [/ruby] 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. [ruby] Dir.foreach('.') do |entry| puts entry end [/ruby] 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 [email protected] Thank you very much for watching, goodbye.
Keep reading...

Programming With Ruby Episode 12, Documentation

Series: Ruby Programming

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 [email protected] Thank you very much for watching, goodbye!
Keep reading...

Programming With Ruby Episode 11, Ruby Projects

Series: Ruby Programming

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: [ruby] require 'rubygems' require 'name' # Name can be a gem or a source file [/ruby] if you are just using a source file, you don't need to require rubygems example: [ruby] require 'rubygems' require 'hpricot' [/ruby] 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 [email protected] Please do not forget to donate, a small $5 or $10 donation will help more than you realize! Thanks for watching, Goodbye.
Keep reading...

Programming With Ruby Episode 10, Objects and Modules

Series: Ruby Programming

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: [ruby] class MyClass end [/ruby] and create them like this: [ruby] variable = MyClass.new [/ruby] You can define methods inside the class: [ruby] class MyClass def hello puts 'Hello!' end end [/ruby] 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 [ruby] class MyClass def initialize @database = connect_to_database end end [/ruby] 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. [ruby] class MyClass def self.game_objects # Return all objects in the game end end [/ruby] 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: [ruby] def words(string) string.scan(/\w[\w\'\-]*/) end words("Hello World") #=> ["Hello", "World"] [/ruby] But it looks a lot nicer, and is more object-oriented if you do this instead: [ruby] class String def words scan(/\w[\w\'\-]*/) end end "Hello World".words #=> ["Hello", "World"] [/ruby] 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: [ruby] 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 [/ruby] 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: [ruby] module DataVisualizer class Grapher end class Plotter end def self.data_compatible? end end [/ruby] To access methods that modules define you simply do: [ruby] module MyModule def self.x end end MyModule.x [/ruby] To access classes defined by modules, you have to use double colons: [ruby] module DataVisualizer class Grapher end class Plotter end end DataVisualizer::Grapher.new [/ruby] 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 [email protected] Than you very much for watching, goodbye!
Keep reading...

Programming With Ruby Episode 9, Flow Control

Series: Ruby Programming

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: [sourcecode language="ruby"] my_array.each do |item| puts item end [/sourcecode] or like this: [sourcecode language="ruby"] my_array.each { |item| puts item } [/sourcecode] 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: [sourcecode language="ruby"] x = 3 if x < 5 # Do something end [/sourcecode] 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: [sourcecode language="ruby"] == < > <= >= != [/sourcecode] 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: [sourcecode language="ruby"] x = 3 if x < 5 # Do something if true else # Do something if false end [/sourcecode] In a similar way you can execute code if the first condition is false but a second is true: [sourcecode language="ruby"] 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 [/sourcecode] In a different way you can only execute the code if two conditions are true: [sourcecode language="ruby"] x = 3 y = 2 if x == 3 and y == 2 # Do something end [/sourcecode] You can also only execute code if one of any conditions are true: [sourcecode language="ruby"] x = 3 y = 4 if x == 3 or y == 2 # Do something end [/sourcecode] There is also the evil twin brother of if, unless: [sourcecode language="ruby"] x = 3 unless x == 3 # if x is 3, this code will not run end [/sourcecode] You can chain all of these together in almost any way you choose. Case, When Another way to evaluate conditions is using case, when: [sourcecode language="ruby"] x = 3 case x when 1 then # do something when 3 then # do something else # do something if none are true end [/sourcecode] 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: [sourcecode language="ruby"] x = 1 while x < 5 x += 1 puts x end [/sourcecode] Similar to the relationship between if, and unless. while has an evil sister, until [sourcecode language="ruby"] x = 1 until x > 5 x += 1 puts x end [/sourcecode] There are also for loops, which allow you to iterate over something [sourcecode language="ruby"] foods = ["ham", "eggs", "cheese"] for food in foods puts food += " is yummy!" end [/sourcecode] There is also .each, for's evil stepchild: [sourcecode language="ruby"] foods = ["ham&", "eggs", "cheese"] foods.each do |food| puts food += " is yummy!" end [/sourcecode] Concrete Example A menu system [sourcecode language="ruby"] 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 [/sourcecode] 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 [email protected] 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!
Keep reading...

Programming With Ruby Episode 8, Hashes

Series: Ruby Programming

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: [sourcecode language="ruby"] my_hash = {} [/sourcecode] Items are defined like this: [sourcecode language="ruby"] birthdays = {"Amy" => "May", "Dakota" => "January"} [/sourcecode] 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: [sourcecode language="ruby"] brithdays["Amy"] #=> May [/sourcecode] You can define new keys and values: [sourcecode language="ruby"] birthdays["Zack"] = "April" [/sourcecode] Iterating Over Hashes Hashes have an each method like arrays do: [sourcecode language="ruby"] 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 [/sourcecode] 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 [email protected] Thanks for watching, goodbye!
Keep reading...

Programming With Ruby Episode 7, Arrays

Series: Ruby Programming

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: [sourcecode language="ruby"] x = [] [/sourcecode] This is an empty array, if we wanted an array with something in it: [sourcecode language="ruby"] todo_list = ["Cut Grass", "Buy Food", "Fix Tom's Computer"] [/sourcecode] 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: [sourcecode language="ruby"] todo_list[0] #=> "Cut Grass" [/sourcecode] You can also add items to an array in a similar way [sourcecode language="ruby"] todo_list[3] = "Go Skydiving" [/sourcecode] Another way to add items is to use +=, which you may recognize from previous tutorials [sourcecode language="ruby"] todo_list += ["Eat Sandwich"] [/sourcecode] 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: [sourcecode language="ruby"] todo_list[0..2] #=> ["Cut Grass", "Buy Food", "Fix Tom's Computer"] [/sourcecode] 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: [sourcecode language="ruby"] todo_list[3..-1] #=> ["Go Skydiving", "Eat Sandwich"] [/sourcecode] Array Iteration If you want to loop over each element of an array you use the each method: [sourcecode language="ruby"] numbers = [1, 2, 3, 4] numbers.each do |number| puts number * 2 end #=> 2 4 6 8 [/sourcecode] You can do the same thing, but turn the output into an array with the collect method: [sourcecode language="ruby"] numbers = [1, 2, 3, 4] numbers.collect do |number| number * 2 end #=> [2,4,6,8] [/sourcecode] 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 [email protected] Thanks for watching, bye!
Keep reading...

Programming With Ruby Episode 6, Strings

Series: Ruby Programming

Covered in this episode:
  • String Literals
  • String Expressions
  • String Methods
  • Regular Expressions
  • Getting User Input (gets)
Transcript: Hello Everyone and Welcome to Programming With Ruby Episode 6, Strings. I'm Tyler, your presenter. This is brought to you by manwithcode.com In this episode I will be telling you what string literals are. I will show you expressions you can use with strings, which are similar but still different than expressions with numbers. I will show you useful methods strings have. I will show you how to use regular expressions. Finally I will teach you how to get input from the user. On to the Code! String Literals According to wikipedia, string literals are the representation of a string value within the source code of a computer program. For example: [sourcecode language="ruby"] puts "Hello World" # Hello World is the string literal [/sourcecode] String Expressons The only string expressions are the plus and multiplication sign. The plus sign connects strings together, the multiplication sign repeats a string a certain number of times. Let me show you how it works: [sourcecode language="ruby"] "Hello " + "World!" #=> "Hello World!" "Hello " * 3 #=> "Hello Hello Hello" [/sourcecode] String Methods Here are some useful String methods: empty? tells you if you are dealing with an empty string length tells you how long a string is each_char lets you iterate over each character capitalize capitalizes the first character upcase makes all characters upper case downcase makes all characters lower case Regular Expressions Regular expressions are a way to match elements in other strings. It is easier to show you than to describe to you, so here we go! The simplest is substitution: [sourcecode language="ruby"] "Hello World".sub("Hello", "Goodbye") #=> "Goodbye World" [/sourcecode] But if you have more than one hello: [sourcecode language="ruby"] "Hello Hello Hello".sub("Hello", "Goodbye") #=> "Goodbye Hello Hello" [/sourcecode] This happens because the sub method only replaces the first occurrence of "Hello". The gsub method fixes this: [sourcecode language="ruby"] "Hello Hello Hello".gsub("Hello", "Goodbye") #=> "Goodbye Goodbye Goodbye" [/sourcecode] What if you want to manipulate parts of a string using regular expressions. The scan method is what you want! [sourcecode language="ruby"] # /n means new line "Who are you".scan(/../) { |x| puts x } #=> Wh\no \nar\ne \nyo # With no whitespace: "Who are you".scan(/\w\w/) { |x| puts x } #=> Wh/nar/nyo [/sourcecode] Regular Expressions are a vast topic that I can't completely cover here, so do a Google search to find out more. Getting User Input You can get user input with the "gets" method: [sourcecode language="ruby"] a = gets # The user inputs: I like pie puts a #=> "I like pie" [/sourcecode] That wraps it up for todays episode. Don't forget to donate, the link is to the right of this video If you have any questions or comments, leave a comment on this page or email me at [email protected] Bye!
Keep reading...

Programming With Ruby Episode 5, Numbers

Series: Ruby Programming

Covered in This Episode
  • Numbers
  • Expressions
  • Types of Numbers
  • Constants (New type of variable!)
  • Doing something a number of times
Transcript Hello Everyone and Welcome to Programming With Ruby Episode 5, Numbers. Its sitll presented by me, Tyler. And brought to you by manwithcode.com In this episode I will be talking about numbers in Ruby. I will go over expressions, the different types of numbers, I will introduce a new variable type called a constant, and will show you how to repeat an action a certain number of times in Ruby. Lets get started! Pop open you Command prompt or Terminal and start Interactive Ruby. If you have forgotten, just enter 'irb'. First item is expressions. [sourcecode language="ruby"] 2 + 2 #=> 4 2 - 2 #=> 0 3 * 3 #=> 9 6 / 3 #=> 2 2 ** 5 #=> 5 [/sourcecode] expressions with variables work in the same way [sourcecode language="ruby"] x = 5 5 * x #=> 25 x ** 4 #=> 625 [/sourcecode] If you want to do math on a variable and set the value of the variable to the result use: [sourcecode language="ruby"] x = 5 x *= 2 #=> x = 10 x -= 4 #=> x = 6 x /= 6 #=> x = 1 [/sourcecode] In Ruby there are 3 different types of numbers. Fixnum, which are 32-bit numbers. Floats, which are numbers with a value after the decimal point. Bignums which are numbers larger than 32-bits. [sourcecode language="ruby"] 5.class #=> Fixnum 0.421.class #=> Float 999999999999 #=> Bignum [/sourcecode] In Ruby it is possible to separate up larger numbers to improve readability in the code. Simply place in underscores [sourcecode language="ruby"] 1_000_000 #=> 1000000 [/sourcecode] Lets say you are writing some code and you need to do something a certain number of times. Use this code: [sourcecode language="ruby"] 2.times do |x| puts x end #=> 0 #=> 1 [/sourcecode] That wraps it up for this episode. If you have any questions or comments, leave a comment in the comment box below. Or email me at [email protected] Don't forget to donate. The button is to the right of this video. Thanks for watching. Goodbye
Keep reading...

Programming With Ruby Episode 4, Main Ruby Concepts

Series: Ruby Programming

Covered In This Episode:
  • Basic Variables
  • Basic Methods
  • Basic Classes
  • Interactive Ruby (irb)
Code: [sourcecode language="ruby"] # Define the class Greeter class Greeter # Define the method hello # This method greets the # user def hello(name) puts "Hello " + name end # End of the method hello end # End of the class Greeter Greeter.new.hello("Tyler") [/sourcecode] Transcript: Hello everybody and welcome to Programming With Ruby Episode 4, Main Ruby Concepts. Covered in this episode. We'll be playing with interactive ruby (also called irb). I will teach you about variables, basic methods, and classes in Ruby. Lets get started! Basics Description Ruby is an object oriented programming language. object oriented languages use objects. Ruby goes beyond most other object oriented languages, because in Ruby, everything is an object. (I'll show you exactly what that means in a few minutes) Object oriented programming sort of models real life. Look around you, everything around you is an object. Your computer, your desk, books, the moon, and people are all objects. In programming, all objects have properties called variables. These could be the color of the object, the weight, size, or any other kind of property. Objects also have methods (which are sometimes called functions). A camera object would have a method to take pictures. A car would have a method to drive. A printer would have a method to print. As well as making code easier to understand, you will also continue to appreciate other benefits of object oriented programming further on in your programming career. Example I have written a very basic Ruby program. This is about what most programs look like, just a lot simpler. Let's break it down line by line. Everything followed by a hash mark (#), is ignored by Ruby. These are called comments. In these comments you can describe what your code is doing, make notes to yourself, and other such things. The first line says "class Greeter". This line tells Ruby that we are now defining a class named "Greeter". Please remember that all classes in Ruby start with a capital letter! The next line says "def hello(name)". This line means we are defining a function (def), named "hello", that takes the parameter "name". The following line is a little trickier. 'puts "Hello " + name'. "puts" means "put string". our string is "Hello " + name. Now you're probably wondering what the "+ name" is for. We're aren't doing math on strings, but we are connecting the variable "name" to our other string "Hello ". The next two lines have the keyword "end". The first end means we are done defining the function "hello". The second "end" means we are done defining the class "Greeter". Below where the class "Greeter" ends we have the line 'myname = "Tyler"'. This means are creating the variable myname and placing "Tyler" inside of it. Next is, the line "person = Greeter.new". This means we are instantiating a new greeter object named person. Finally we have the line "person.hello(myname)". This calls the person object's method "hello" and passes the variable "myname" as an argument. Now lets run the program. If you remember, to run a program you open Terminal or Command Prompt, change directories into where you saved your program and type "ruby programname.rb". In my case I will type "ruby episode4.rb". And there you have it, it says "Hello Tyler" The code in this example will be available in the YouTube video description, and below this video on manwithcode.com Example 2 Back to the code. This code is actually a little longer than it has to be. I did this so things would hopefully make more sense. In reality we can change the last three lines to 'Greeter.new.hello("Tyler")' We can do this because in Ruby, everything is an expression. Here's how it breaks down. "Greeter.new" creates a greeter object. ".hello" calls the method "hello" on that new object. And then we pass in the string "Tyler" as an parameter. Ruby has many other tricks like this to make your code shorter. Some have disadvantages and others do not. One of the most important disadvantages can be clarity or readability. You want your code to be as easy to understand as possible. irb Interactive Ruby (or irb for short). irb makes it very easy to quickly test out code, find out if/how something works, do basic math, and write throwaway code you will only use once. To open irb, open up your Command Prompt or Terminal and enter irb. Alternatively, if you are on Windows, go into All Programs and under Ruby will be a program name fxri which is an equivalent to irb. In irb you can do basic math: [sourcecode language="ruby"] 2 + 2 #=> 4 2**6 #=> 64 2 * 5 #=> 10 [/sourcecode] We can write any valid Ruby code. So we could write the greet method again. [sourcecode language="ruby"] def greet(name) puts "Hello " + name end [/sourcecode] And then call it: [sourcecode language="ruby"] greet("Tyler") [/sourcecode] Remember earlier I said everything in Ruby was an object? I'll show you what I mean. if you type in the name of an object and call the class method it will tell you its class. [sourcecode language="ruby"] 0.class #=> Fixnum "Hello".class #=>; String String.class #=> Class [/sourcecode] I encourage you to play around with irb for a little while, try writing your own methods, and have some fun with it. End This brings us to the end of this episode, I hope it helped you.  If you need any help, have questions or comments, leave a comment below or contact me at [email protected] Don't forget to donate! There is a donation link to the right of this video. On YouTube its in the description box. On my website, it is to the right of the video. Thanks for watching! Bye!
Keep reading...

Programming With Ruby Episode 3, Getting Help/Tools

Series: Ruby Programming

Covered in this episode:
  • How to get help
  • Google
  • Ruby's Documentation
  • Forums/Mailing Lists
  • Blogs on Ruby
  • Text Editors
  • Integrated Development Environments (IDEs)
Links: Ruby-Lang: http://www.ruby-lang.org Ruby-Doc:  http://www.ruby-doc.org/ Forums: http://www.ruby-forum.com/ http://www.rubyforums.com/ Text Editors: Notepad++ http://notepad-plus.sourceforge.net/uk/site.htm SciTE http://www.scintilla.org/SciTE.html jEdit http://www.jedit.org/ Text Mate http://macromates.com/ IDEs Netbeans http://www.netbeans.org/ Aptana Rad Rails http://www.aptana.com/ FreeRIDE http://rubyforge.org/projects/freeride/ Geany http://www.geany.org/ More... http://rubyforge.org/softwaremap/trove_list.php?form_cat=65 Transcript Hello Everybody! And Welcome to Programming with Ruby Episode 3, Getting Help and Tools. I'm your presenter, Tyler. This video is brought to you by manwithcode.com Covered in this Episode. I'll be going over how to get help. If you ever get stuck while using Ruby you're first stop should be Google, to some this may sound obvious, but some people still don't use Google. Your next stop would be Ruby's Documentation. Then I will be showing you forums and mailing lists where you can ask for help or help others. Also I will be showing you some blogs by Ruby Developers. On the tools side, I will be showing you some good Text Editors, and a few IDEs (or Integrated Development Environments). Just as a side note, I will be showing many websites today, but don't worry, all links are in the description Lets Get Started! Out first stop will be Google. Lets say I wanted to learn about Ruby Lambdas just type in "ruby lamdas" and you get a list of relavant web pages. I'll pick the first link, and here is some information on how to use lambdas. If Google can't help you, lets look at the official Ruby Documentation. This is ruby-doc.org. It has some articles and tutorials on Ruby. But what we are interested in is the part that says "Core API" we are using the 1.8 version of Ruby, so we will visit the 1.8.6 core link and here is the documentation for Ruby! lets say I wanted to look for lambdas again, I'll hit CTRL-F for the browsers find funtion, and type in "lambda" and here is the information I want, I'll click the link, and there is the documentation! Okay lets say that a Google search and a look through the documentation doesn't help you with your problem. What do you do? You ask a person, of course! This is where the forums come in. There are two forums that I like, there is ruby-forum.com And rubyforums.com both of which you can post on and will hopefully get answers For general tips and news about Ruby, you may be interested in some blogs about Ruby. To find some, lets go to ruby-lang.org click on the community link. scroll down, and click the "weblogs about ruby" link and here there are some blogs, and aggregators listed So hopefully if you have a problem all these resources should be able to help you. Now we are going to move onto tools. First stop Text Editors. There are a few good text editors available, so I will just highlight a few. If any of these look interesting, remember that all links are in the description. First is Windows only text editor notepad++, the editor I use on Windows Then is SciTE, a scintilla based editor Jedit is a popular text editor that is written in Java Text mate is a very popular text editor for the Macintosh that costs $55 For Linux there are editors like gEdit and Kate which have some of the features of the editors mentioned above. Even if you like your featureless plain text editor like notepad, features the previously mentioned editors have make writing code much easier, and I recommend you get one. First we have netbeans, which is my IDE of choice. Even though it was originally for Java, it works very well with Ruby Next is Aptana rad rails, an IDE which many people like, but was too buggy on my computer, it is especially useful if you are using Ruby on Rails freeRIDE is a popular editor for ruby Geany is a GTK based editor for Linux that works with many different languages These are all very good editors, but because you are currently learning I would just recommend a text editor for now, when you start developing larger projects an IDE can be very useful. This brings us to the end of this episode, I hope it helped you. If you need any help, have questions or comments, leave a comment below or contact me at [email protected] Hey! before you go, you may have realized that I am making these videos for free if they have helped you at all please donate. If you viewing this on Youtube there is a donation link to the right in the description box. If you are on my site there is a donation button to the right Thanks for watching! Bye!
Keep reading...

Programming With Ruby Episode 2, Getting Started

Series: Ruby Programming

Covered in this episode:
  • Installing Ruby
  • What you will need
  • Hello World! program
Transcript Hello everybody and welcome to Programming with Ruby Episode 2 - Getting Started. I'm the presenter, as always, Tyler. This is brought to you by manwithcode.com. This is ruby-lang.org. Go to the downloads section. There are a bunch of links here. If you are on Windows, go to the Ruby One-Click Installer. It is a standard installer, like any other Windows program. If you are on a Debian variant of Linux (such as Ubuntu). The line: sudo apt-get install ruby irb rdoc will get you what you need If you are on mac OSX, you can install ruby with mac ports via the command: port install ruby alternatively you can go to the ruby OSX one click installer (http://rubyosx.rubyforge.org/), be sure to the installer for version 1.8.7 not 1.9.1 If you are compiling from source, compile 1.8.7 NOT 1.9.1 To get started you will need a text editor, like Notepad. It needs to be plain text editor, we don't want any of the formatting that programs like Word put on there. My editor of choice is gEdit, which comes with the GNOME desktop on Linux. Alternatively you can use an IDE, like Netbeans or Geany. Open up your text editor, and type in: [sourcecode language="ruby"] puts "Hello World!" [/sourcecode] save that to your desktop as hello.rb There are two ways of running this. If you are on Windows, go to where you saved it and double click on it. Or you can open up the Command Prompt/Terminal. Change directories to where you saved the files and type in: ruby hello.rb Questions or Comments Leave a comment on this page or email me at [email protected]
Keep reading...

Programming With Ruby Episode 1, Introduction

Series: Ruby Programming

Covered in this episode:
  • What this series is about
  • A Short History of programming languages
  • What is Ruby (and who makes it)
  • What is Ruby used for
  • Who am I
  • Why am I teaching this
Transcript Hello everybody and welcome to Programming with Ruby Episode 1, Introduction What this series is about By the end of this series you should be able to effectively use the programming language, Ruby Short History of Programming Languages when it all first started out, everything was just 1s and 0s, it was hard to use, and difficult to debug then it got a little better when assembly came along. You had words like MOV that translated into the corresponding 1s and 0s. compiled by and assembler then came COLBOL and FORTRAN then C, which was better, but still sucked then C++ which brought object orientation to the world then Python and Ruby. they are both object oriented and very easy to use. What is Ruby? A programming language, that supports many different kinds of programming paradigms, and is fully object oriented Ruby was created by Yuukihiro "Matz" Matsumoto Matz designed Ruby to be natural, not simple. I think he achieved that. What is Ruby Used For? Ruby is used a lot for Web Applications Computer Administration Task Automation Game Programming And almost anything else The only thing you might want to stay away from are things that are computationally expensive, like image processing. Who am I? I am Tyler J Church I run the sites Man With Code (manwithcode.com) and ruby game dev (rubygamedev.wordpress.com) Why am I Teaching This? It is the tutorial I never had. I was look for something like this when I started learning Ruby. I didn't want to read a bunch, I wanted to watch videos, but nothing like that existed I think video is the best way to learn I want to give back to the community. That brought me Ruby, that helped me learn. Thank You! Questions or Comments Leave a comment on this page or email me at [email protected] Thanks for reading!
Keep reading...