Ruby:Tutorial

From GPWiki

Files:GUITutorial_warn.gif The Game Programming Wiki has moved! Files:GUITutorial_warn.gif

The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server.

However, the GPWiki forums are still active! Come say hello.

Contents

Getting Ruby

Windows

  1. Download the Ruby 1.8.5 One-Click Installer
  2. Install
  3. Profit

Linux

  1. If you use Ubuntu you can install it via "sudo apt-get install ruby irb rdoc"
  2. Otherwise see the Ruby download section for instructions
  3. Profit

Mac OS X

  1. Head to the download section on the Ruby website
  2. Install it using DarwinPorts
  3. Profit

Hello World

Ruby is pretty straightforward. Why? Well...

puts "Hello World"

Or the more sophisticated version (from the ruby website):

# The famous Hello World
# program is trivial in
# Ruby. You don't need:
#
# * a "main" method
# * newline escapes
# * semicolons
#
# Here's the code:
 
puts "Hello World!"

Classes

The following example demonstrates a Person class:

class Person
    attr_accessor :name, :age, :height, :weight
 
    def initialize(name, age, height, weight)
        @name = name
        @age = age
        @height = height
        @weight = weight
    end
 
    def information
        print "Name: #{name}\n Age: #{age}\n Height: #{height}\n Weight: #{weight}\n"
    end
end

One could use the class like so:

smith = Person.new("Mr Smith", 20, 5.11, 13.5)
smith.information

Would output:

Name: Mr Smith
Age: 20
Height: 5.11
Weight: 13.5