Monthly Archives: June 2009

Ruby Tutorial #2

There are very few programming fundamentals but an infinite way of using and expressing them.

I will start with two basic types – Strings and Integers.

A string is an ordered sequence of zero or more characters.
An integer is any whole natural number.

Ruby is a weakly typed language meaning that you don’t need to predetermine a variables type at declaration, rather it is dynamically set (and reset) at assignment.

message = “hello world” #string
puts message
puts message.class

message = 42 #integer/fixnum
puts message
puts message.class

The key parts of the above script are:
message: a variable
puts: prints to the console
#: a comment. Anything following the # is ignored.
.class: is a method of Object (message in this case)

Don’t worry if all these terms don’t make complete sense yet.

Some other methods to try out are:

puts message.reverse
puts message.upcase
puts message.length
puts message[0..4]

Strings can be changed and manipulated. The plus sign is concatenation eg.

message = “hello world”
message = message[0..5] + ‘mum’
puts message

Appending a ! on the end will change the contents of the variable in place.

message = “Hello Mum”
puts message
message.swapcase!
puts message

Ruby treats everything as an object. For example

puts “hi mum”.length

And you can chain methods together

puts “Hello muM”.upcase.swapcase

Beginning Ruby in Netbeans 6.5.1

The most recent versions of Netbeans (6+) have become very usable and are improving rapidly. Probably not as feature rich as Eclipse but faster and certainly not lacking in professional capability. Netbeans is currently my IDE of choice for ruby and rails development.

I intend to write a series of tutorials for my brother to gently introduce him to programming in ruby.

Lets begin.

Download Netbeans here. You have two choices you can get the Ruby package (about 60mb) or the whole suite (240mb).

Tutorial 1.

  1. Launch Netbeans
  2. File -> New Project..
  3. Select “Ruby Application”. Click “Next”
  4. Give your project a name and a location to save it. In this instance I am calling it “RubyTutorial” and saving it in my “workspace” directory. Click “Finish”.
  5. Now you are in the project environment. In the right pane the tab should say “main.rb”. Click on the “Run” button (or press F6)

The Output pane should be visible now with the words “Hello World”

Congratulations you have just run a basic ruby program.

In the code pane you will see the line:

puts “Hello World”

You can change what is between the quotes to anything you like. Press the run button (or F6) to see what happens. Any line beginning with # is a comment and won’t affect the execution of the program.