Ruby Introduction

Congratulations, you have now installed Ruby on Rails. To start, let’s get a feel for Ruby.

“Hello World”

Writing a simple Hello World program is easy in Ruby. Start a command window (Start -> Run -> “cmd”), then type:

irb

to bring up interactive Ruby. You should see:

C:\Documents and Settings\Suzanne>irb
irb(main):001:0>

Now type:

puts "Hello World"

You will see:

irb(main):001:0> puts "Hello World" 
Hello World
=> nil
irb(main):002:0>

Bingo! Hello World in just one line of code!

“Hey World” Method

Okay, that was kind-of cheating since Ruby is very interactive. Let’s see how much more difficult it is to write a method to say “Hey World”:

def hey_world
  puts "Hey World" 
end
hey_world

You will see:

irb(main):002:0> def hey_world
irb(main):003:1>   puts "Hey World" 
irb(main):004:1> end
=> nil
irb(main):005:0> hey_world
Hey World
=> nil
irb(main):006:0>

“Yo World” Class

That still wasn’t too hard, was it? Okay, but Ruby is an object language, and so far it doesn’t seem like we have been using objects. So lets do a “Yo World” program with an object:

class YoWorld
  def say
    puts "Yo World" 
  end
end
yo_world = YoWorld.new
yo_world.say

You will see:

irb(main):015:0*   class YoWorld
irb(main):016:1>     def say
irb(main):017:2>       puts "Yo World" 
irb(main):018:2>     end
irb(main):019:1>   end
=> nil
irb(main):020:0>
irb(main):021:0*   yo_world = YoWorld.new
=> #<YoWorld:0x28aa488>
irb(main):022:0>   yo_world.say
Yo World
=> nil
irb(main):023:0>

Still not very hard at all!

“Yo” Program

Okay, that is pretty easy, but it is still not a program, right? Isn’t actually writing a program instead of using interactive Ruby much more difficult? Well, not really. Copy this to “yo.rb”

class Yo
  def say
    puts "Yo" 
  end
end
yo = Yo.new
yo.say

Now exit irb (type “exit” and from the command prompt type:

ruby yo.rb

You will see:

C:\>copy con yo.rb
class Yo
  def say
    puts "Yo" 
  end
end
yo = Yo.new
yo.say
^Z
      1 file(s) copied.
C:\>ruby yo.rb
Yo
C:\>

Writing an object-oriented program can’t get much easier than that!

Ruby Complexities

Are you asking yourself, “Is that is hard as it gets?” Well, there are some more complex parts of Ruby that exposes some very powerful functionality, but Ruby just generally makes good sense.

Here are some aspects of Ruby that have confused people:

  • Single versus double quotes
  • @variable versus variable
  • :symbol versus ‘symbol’
  • Hashes and the => operator

Ruby Reference

The reference I use all the time for Ruby is:

Programming Ruby: The Pragmatic Programmer’s Guide

You can walk through each chapter on this site and learn Ruby through its excellent tutorial.

If you just want a reference for Ruby commands, here is a good spot:

Ruby classes and modules