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."
Matz (Yukihiro Matsumoto), Ruby creator, says:
"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."
"For me the purpose of life is partly to have joy. Programmers often feel joy when they can concentrate on the creative side of programming, So Ruby is designed to make programmers happy."
"I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python."
Ruby is...
$ irb
>> 4
=> 4
>> 4+4
=> 8
Please fire up irb
on your computer and try this out right now!
>> 2.class
=> Fixnum
>> 2.to_s
=> "2"
>> 2.to_s.class
=> String
>> 2 + 2
=> 4
>> (2+2).zero?
=> false
>> if true then "yes" end
=> "yes"
>> if false then "yes" end
=> nil
>> puts "foo"
foo
=> nil
The output is foo\n
but the value is nil
.
fruit = "apple"
fruit
is the name of an object containing apple
print
prints its argputs
prints its arg plus a newlinep
inspects and prints its arg plus a newlinepp
pretty-prints its arg plus a newline
require "pp"
ap
is even prettier than pp
d
is even prettier than ap
wrong
gemrequire "wrong"; include Wrong::D
d { x }
prints x is 10
def add a, b
a + b
end
add 2, 2
#=> 4
def add(a, b)
is also legalsemicolons, parens, and return
are optional
These are equivalent:
def increment(x)
return x + 1;
end
def increment x
x + 1
end
def increment x; x + 1; end
def increment(x) x + 1; end
map
iterator translates each item in an array into a new array>> ["hello", "world"].map {|string| string.upcase}
=> ["HELLO", "WORLD"]
{|string| string.upcase}
defines a blocks = "my dog has fleas"
Without chaining:
words = s.split
words = words.map{|word| word.capitalize}
s = words.join(" ")
With chaining:
s = "my dog has fleas"
s.split.map{|word| word.capitalize}.join(" ")
Other languages are prose:
public String titleize(s) {
String words = s.split(" ");
String titleized = "";
for(int i =0; i < words.length ; i++) {
char capLetter = Character.toUpperCase(words[i].charAt(0));
String capWord = capLetter + words[i].substring(1, words[i].length());
titleized += capWord + " ";
}
return titleized.trim();
}
Ruby is poetry:
def titleize s
s.split.map(&:capitalize).join(" ")
end
Cf. declarative vs. algorithmic
2 + 2 # is a comment ```
Ruby has a syntax for multiline comments too, but it's silly and nobody uses it.
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
=> "hello"
>> "Hello".gsub("H", "h").reverse
=> "olleh"
first_name = "Santa"
last_name = "Claus"
full_name = first_name + last_name
#=> "SantaClaus"
42
(Fixnum)3.14159
(Float)true
false
"apple"
'banana'
:apple
["apple", "banana"]
(1..10)
{:apple => 'red', :banana => 'yellow'}
{apple: 'red', banana: 'yellow'}
/fo*/i
"boyz #{1 + 1} men"
=> "boyz 2 men"
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
Ruby Cheat Sheets from Ruby Inside
see also The Well-Grounded Rubyist, p. 5, section 1.1.2
Are you sick of hearing me speak?
If so, do a lab: 01_temperature is right up your alley.
my_array = ["cat", "dog", "world"]
my_array.each do |item|
puts "hello " + item
end
do...end
defines a block
item = "cat"
item = "dog"
item = "world"
class Calculator
def add(a,b)
a + b
end
end
calc = Calculator.new
calc.add(2, 2)
#=> 4
Object
if nothing else.
) sends a message to an objectself
) is the receiver!
or ?
?
means "boolean"!
means "watch out!"methods and variables are in snake_case
classes and modules are in CamelCase
constants are in ALL_CAPS
Standard is better than better.
-- Anon.
local_variable
- start with letter or underscore, contain letters, numbers, underscored@instance_variable
- start with @
@@class_variable
- start with @@
$global_variable
- start with $
Constant
or CONSTANT
- must start with uppercase letterClassName
- capitalized camel casemethod_name?
- like a local variable, but can end with ?
or !
or =
def
) and weirdos (__FILE__
)"hi"
for strings, [1,2]
for arrays, {:a=>1, :b=>2}
for hashes, etc.var # local variable (or method call)
@var # instance variable
@@var # class variable
$var # global variable
VAR # constant
load
and require
load
inserts a file's contents into the current filerequire
makes a feature available to the current file
.rb
.so
, .dll
, etc.)/