Introduction to Ruby for Programmers

This section is intended as a brief, lightweight overview of the Ruby language; following sections will cover all these topics in much more detail. Students are encouraged to ask questions, but instructors are encouraged to answer, "We'll cover that later."

(Originally based upon Ruby Quickstart for Refugees but improved by many.)

Ruby vs. Rails

Ruby is a Language

Rails is a Framework

Rails is written in Ruby

Ruby Philosophy

Q: Did you have a guiding philosophy when designing Ruby?

A: Yes, it's called the "principle of least surprise."

I believe people want to express themselves when they program.

They don't want to fight with the language.

Programming languages must feel natural to programmers.

I tried to make people enjoy programming and concentrate on the fun and creative part of programming when they use Ruby.

  - Matz (Yukihiro Matsumoto), Ruby creator

Ruby Philosophy, Applied

Many Rubies

Versions common today

Ruby Language Overview

IRB: Interactive RuBy

Type irb in the terminal to launch IRB

>> 4
=> 4
>> 4+4
=> 8

Please fire up irb on your computer and try this out!

Everything evaluates to something

>> 2 + 2
=> 4

>> (2+2).zero?
=> false

>> "foo" if false
=> nil

>> puts "foo"
foo
=> nil

Hash mark comments, like perl

# is a comment
2 + 2 # is a comment

Optional semicolons, parens, and return

These are equivalent:

def inc x
  x + 1
end

def inc(x)
  return x + 1;
end

def inc(x); x + 1; end

Line Break Gotcha

x = 1 + 2
x #=> 3

x = 1
  + 2
x #=> 1

Solution: always put operators on top line

x = 1 +
    2
x #=> 3

Use parens when you need them

>> "Hello".gsub 'H', 'h'
=> "hello"

>> "Hello".gsub("H", "h").reverse
=> "olleh"

Variables are declared implicitly

first_name = "Santa"
last_name = "Claus"
full_name = first_name + last_name
#=> "SantaClaus"

String interpolation

"boyz #{1 + 1} men"
=> "boyz 2 men"

Built-in Types

Functions

def add(a,b)
  a + b
end

add(2, 2)
#=> 4

Classes and methods

class Calculator
  def add(a,b)
    a + b
  end
end

bang and question methods

equal, double-equal, and threequal

Ruby syntax cheatsheet

cheatsheet

(_The Well-Grounded Rubyist_, p. 5, section 1.1.2)

Ruby identifiers

Ruby Naming Conventions

methods and variables are in snake_case

classes and modules are in CamelCase

constants are in ALL_CAPS

Standard is better than better.

-- Anon.

Variable Scopes

var   # local variable (or method call)
@var  # instance variable
@@var # class variable
$var  # global variable
VAR   # constant

Messages and Methods

Classes

load and require

Credits

[contents]

deck.rb presentation

/

#