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.)
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
Type irb
in the terminal to launch IRB
>> 4 => 4 >> 4+4 => 8
Please fire up irb
on your computer and try this out!
>> 2 + 2 => 4 >> (2+2).zero? => false >> "foo" if false => nil >> puts "foo" foo => nil
# is a comment 2 + 2 # is a comment
return
These are equivalent:
def inc x x + 1 end def inc(x) return x + 1; end def inc(x); x + 1; end
x = 1 + 2 x #=> 3 x = 1 + 2 x #=> 1
Solution: always put operators on top line
x = 1 + 2 x #=> 3
>> "Hello".gsub 'H', 'h' => "hello" >> "Hello".gsub("H", "h").reverse => "olleh"
first_name = "Santa" last_name = "Claus" full_name = first_name + last_name #=> "SantaClaus"
"boyz #{1 + 1} men" => "boyz 2 men"
42
true
false
"apple"
'banana'
:apple
["apple", "banana"]
{:apple => 'red', :banana => 'yellow'}
(1..10)
def add(a,b) a + b end add(2, 2) #=> 4
class Calculator def add(a,b) a + b end end
!
or ?
!
means "watch out!"?
means "boolean"x = 1
means "put the value 1
in the variable x
"x == 2
means "true
if x
is 2
, otherwise false
"x === 3
means the same as ==
but sometimes more(_The Well-Grounded Rubyist_, p. 5, section 1.1.2)
local_variable
- start with letter or underscore, contain letters, numbers, underscored@instance_variable
- start with @
@@class_variable
- start with @@
$global_variable
- start with $
Constant
- start with uppercase lettermethod_name?
- same as local, but can end with ?
or !
or =
def
) and weirdos (__FILE__
)"hi"
for strings, [1,2]
for arrays, {:a=>1, :b=2}
for hashesmethods and variables are in snake_case
classes and modules are in CamelCase
constants are in ALL_CAPS
Standard is better than better.
-- Anon.
var # local variable (or method call) @var # instance variable @@var # class variable $var # global variable VAR # constant
.
) sends a message to an objectself
) is the receiverObject
if nothing elseload
and require
load
inserts a file's contents into the current filerequire
makes a feature available to the current file
.rb
.so
, .dll
, etc.)/
#