Learn Programming with Ruby

What is Programming?

The purpose of programming is to create a set of instructions for computers to perform in order to achieve specific goals. At the lowest level, computers are binary. All data and operations are represented as of 1s (on) and 0s (off).

History

Installing Ruby

Mac

Ruby comes pre-installed on Mac OS X and on several Linux distributions. Open up the Terminal application and type:

ruby -v

If you see a version number, then Ruby is already installed on your machine. Otherwise, download it here.

Windows

Download Ruby 1.9.3-0392

Pick a Text Editor

Using IRB (Interactive Ruby Shell)

Allows the use of Ruby code from the command line

Mac

  1. Open the Terminal Application
  2. Type irb and press enter

Windows

  1. Start -> All Programs -> Ruby -> Start Ruby with Command
  2. Type irb and press enter

Basic data types

Integers

Whole numbers, no fractions allowed. You can perform mathematical operations on integers.

>> 1 + 1
=> 2
>> 6 / 3
=> 2
>> 2 ** 3
=> 8
>> (3 + 5) / (1 + 3)
=> 2
Read more on Integers

Strings

>> puts "Hello World"
Hello World
=> nil
>> puts "Hello " + "World"
Hello World
=> nil
Read more on Strings

Methods

These are actions that piece of data can perform or be performed on.

>> "Hello World".reverse
=> "dlroW olleH"
>> "Hello World"[0].chr
=> "H"
>> "Hello World"[-1].chr
=> "d"

Variables

A piece of data that is labeled and stored. You can change contents of the data. Variables can be used in place of real data when using methods.

>> name = "Chewbacca"
=> "Chewbacca"
>> puts name
Chewbacca
>> letters = name.length
=> 9
>> puts letters
9
=> nil

Input in the Console

You can use the gets method to retrieve input from the console.

>> name = gets.chomp
#type in your name
=> "Your name"
>> puts "Hi #{name}"
=> "Hi Your name"

Running Ruby from a File

In order to run Ruby code from a more permanent location, you can save your code in a file with the extension .rb