Upload
overdue-books-llc
View
1.183
Download
0
Embed Size (px)
DESCRIPTION
A slide presentation I gave at OSCON 2007 in Portland, Oregon on the Ruby programming language.
Citation preview
Learning Ruby
Mike FitzgeraldOSCON 2007
July 23, 2007 2
Thank you“Matz”Matsumoto Yukihiro
July 23, 2007 3
Today’s schedule
8:30–9:40 AM: Instruction (70 minutes)
9:40–9:50 AM: Break (10 minutes)
9:50–11:00 AM: Instruction (70 minutes)
11:00–11:10 AM: Break (10 minutes)
11:10 AM–12 noon: Instruction (50 minutes)
July 23, 2007 4
Ruby history
• Matz had wanted to create his own language since high school
• Development started in 1993• First release was in 1995 (same
time as Java)• Emerged in the West around 2000• Ruby on Rails brought it wide
attention in 2004
July 23, 2007 5
What is Ruby?
• Object-oriented scripting language• Open source• Mature and stable• Complex language with a simple
syntax
July 23, 2007 6
What is Ruby? continued
• Interpreted rather than compiled• Core written in C • Can write C extensions, too• Borrows ideas from Lisp, Perl,
Smalltalk, etc.
July 23, 2007 7
Numbers
• Numbers are not primitives but objects
• Most operators are methods• No declarations or static types• Dynamic typing• Duck typing, a kind of dynamic
typing
July 23, 2007 8
Numbers continued
• No increment (++) or decrement (--) operators in Ruby
• Abbreviated assignment operators, such as +=, -=, *=, etc.
• Underscores ignored (1_000_000)• Ranges: 1..10 (inclusive) or 2...5
(exclusive)• Math module: Math.sqrt, Math.sin, etc.
July 23, 2007 9
$ which ruby # [Li|U]nix only
/usr/local/bin/ruby
$ ruby --version
ruby 1.8.6 (2007-03-13 patchlevel 0) [powerpc-darwin8.9.0]
$ irb # Interactive Ruby
irb(main):001:0>
July 23, 2007 10
Running a Ruby program(Windows, [Li|U]nix])
July 23, 2007 11
$ ruby hello.rb
July 23, 2007 12
“Hello, world”or
Printing a string to standard output
July 23, 2007 13
print "Good morning!"
July 23, 2007 14
puts "Hello, Portland."
July 23, 2007 15
Comments
July 23, 2007 16
# say hello
puts "Hello!"
July 23, 2007 17
puts "Hello!" # say hello
July 23, 2007 18
Block comments
July 23, 2007 19
=begin
Say hello to all the
nice people out there.
=end
puts "Hello!"
July 23, 2007 20
Concatenating strings
July 23, 2007 21
print "I like ", "trees."
July 23, 2007 22
puts "I like " + "sushi."
July 23, 2007 23
puts "I like " << "Powell’s."
July 23, 2007 24
Shebang ([Li|U]nix)
July 23, 2007 25
#!/usr/bin/env ruby
puts "Hello!"
July 23, 2007 26
$ chmod 755 hello.rb
$ hello.rb
July 23, 2007 27
Inserting shell output using backticks
July 23, 2007 28
puts "Running " + `ruby -v`
July 23, 2007 29
Issuing a system (shell) command
July 23, 2007 30
system "echo 'Hello, Matz!'"
July 23, 2007 31
Evaluating an expression
July 23, 2007 32
eval "puts 'Hi there.'"
July 23, 2007 33
$ ruby -e "puts 'Hi there.'"
July 23, 2007 34
Multiplicity
July 23, 2007 35
puts "Go!" * 3
July 23, 2007 36
3.times { print "Go! " }
July 23, 2007 37
Variables
• Local variable: start with lowercase letter or _
• Instance variables in class: @name• Class variables: @@times• Global variables: $amount
July 23, 2007 38
hello = "Hello, universe!"
puts hello
July 23, 2007 39
good = "Guten "
day = "Tag"
puts good + day
July 23, 2007 40
x = 9
y = 18
puts x + y
July 23, 2007 41
Parallel assignment
July 23, 2007 42
x, y = 37, 63
July 23, 2007 43
a, b, c = "15", "tons", "200.0"
July 23, 2007 44
c, d = 15, "tons"
July 23, 2007 45
Symbols
• Special object in Ruby• Placeholders for identifiers and
strings• Begin with colon (:)• Not directly created through
assignment• Efficient: Only one copy held in a
single memory address
July 23, 2007 46
name = "Javert"
name.to_sym # => :Javert
July 23, 2007 47
:Javert.id2name # => "Javert"
name == :Javert.id2name # true
July 23, 2007 48
Expression substitution
July 23, 2007 49
x, y = 37, 63
puts #{x + y}
July 23, 2007 50
name = "guy"
puts "Hi, #{name}!"
July 23, 2007 51
Retrieving command-line arguments
July 23, 2007 52
#!/usr/bin/env ruby
puts "Hello, #{ARGV[0]}!"
July 23, 2007 53
$ arg.rb everybody
July 23, 2007 54
Formatting output
July 23, 2007 55
sprintf( "Hello, %s!", "Tim" )
July 23, 2007 56
printf( "Hello, %s!", "Sam" )
July 23, 2007 57
hi = "Hello, %s"
puts hi % "people!"
July 23, 2007 58
"%s, %s!" % [ "Hello", "Tim" ]
July 23, 2007 59
Getting input from the prompt
July 23, 2007 60
#!/usr/bin/env ruby
print "Say hello to..."
hi = gets
puts "Hello, " + hi
July 23, 2007 61
$ get.rb
July 23, 2007 62
Define and call a method
July 23, 2007 63
def hello
puts "Hello"
end
hello
July 23, 2007 64
Aliasing a method
July 23, 2007 65
alias hi hello
hi
July 23, 2007 66
Undefining a method
July 23, 2007 67
undef hello
July 23, 2007 68
Defining a method with an argument
July 23, 2007 69
def hello( who )
puts "Hello " + who + "."
end
hello "Yuri"
July 23, 2007 70
def repeat( word, times )
puts word * times
end
repeat "Go! ", 3
July 23, 2007 71
Return a value explicitly
July 23, 2007 72
def hello
return "Hello."
end
July 23, 2007 73
Defining a method with a defaultvalue for an argument
July 23, 2007 74
def hello( who="Schlomo" )
puts "Hello " + who + "."
end
hello
July 23, 2007 75
Defining a method with a variable
number of arguments
July 23, 2007 76
def hello( *args )
puts args.size
end
July 23, 2007 77
def two_plus( one, two, *args ) length = args.size label = length == 1 ? " variable argument" : " variable arguments"
num = length.to_s + label + " (" + args.inspect + ")"
numend
puts two_plus( 1, 2 )
July 23, 2007 78
Yielding a block
July 23, 2007 79
def hello
yield
end
hello { puts "Hello, Matz." }
July 23, 2007 80
Defining and calling a procedure (proc)
July 23, 2007 81
proc = lambda { puts "Hello!" }
proc.call
July 23, 2007 82
Calling the each method
July 23, 2007 83
["Hi","Mel"].each {|e| print e}
July 23, 2007 84
XML
July 23, 2007 85
<hello>there!</hello>
July 23, 2007 86
#!/usr/bin/env ruby
require "rexml/document"
file = File.new( "hello.xml" )
doc = REXML::Document.new file
puts doc.to_s
July 23, 2007 87
Conditional statements
July 23, 2007 88
if
July 23, 2007 89
x, y = 45, 32
if x > y then
puts "x is greater than y"
end
July 23, 2007 90
if hi == false: puts "Goodbye" end
July 23, 2007 91
if hi == true
puts "Hi"
end
July 23, 2007 92
if !hi == false
puts "Hello!"
end
July 23, 2007 93
Multiple tests
July 23, 2007 94
if ruby=="nifty" && programming=="fun"
puts "Keep programming!"
end
July 23, 2007 95
if ruby=="nifty" and programming=="fun"
puts "Keep programming!"
end
July 23, 2007 96
if a == 10 || b == 27
print a + b
end
July 23, 2007 97
if a == 10 or b == 27
print a + b
end
July 23, 2007 98
Statement modifier for if
July 23, 2007 99
puts "x is less than y" if x < y
July 23, 2007 100
Using else
July 23, 2007 101
if x >= y
puts "x greater than or equal to y"
else
puts "x not greater than or equal to y"
end
July 23, 2007 102
Using elseif
July 23, 2007 103
if x == y puts "x equals y"elsif x != y puts "x is not equal to y"elsif x > y puts "x is greater than y"elsif x < y puts "x is less than y"elsif x >= y puts "x is greater than or equal to y"elsif x <= y puts "x is less than or equal to y"else puts "Arrrrgh!"end
July 23, 2007 104
Using the colon
July 23, 2007 105
lang = "de"
if lang == "en": print "dog"
elsif lang == "es": print "perro"
elsif lang == "fr": print "chien"
elsif lang == "de": print "Hund"
else puts "dog"
end
July 23, 2007 106
The negated form of if: unless
July 23, 2007 107
if lang == "de"
dog = "Hund"
else
dog = "dog"
end
July 23, 2007 108
unless lang == "de"
dog = "dog"
else
dog = "Hund"
end
July 23, 2007 109
Statement modifier for unless
July 23, 2007 110
puts num += 1 unless num > 88
July 23, 2007 111
while
July 23, 2007 112
i = 0breeds = [ "quarter", "arabian", "appaloosa", "paint" ]
puts breeds.size # => 4temp = []
while i < breeds.size do temp << breeds[i].capitalize i +=1end
July 23, 2007 113
temp.sort! # => ["Appaloosa", "Arabian", "Paint", "Quarter"]
breeds.replace( temp )
p breeds # => ["Appaloosa", "Arabian", "Paint", "Quarter"]
July 23, 2007 114
temp = 98.3
begin print "Your temperature is " + temp.to_s + " Fahrenheit. "
puts "I think you're okay." temp += 0.1end while temp < 98.6
July 23, 2007 115
while i < breeds.size
temp << breeds[i].capitalize
break if temp[i] == "Arabian"
i +=1
end
p temp # => ["Quarter", "Arabian"]
July 23, 2007 116
Statement modifier for while
July 23, 2007 117
cash = 100_000.00
sum = 0
cash += 1.00, sum while cash < 1_000_000.00 # _ ignored
July 23, 2007 118
The negated form of while: until
July 23, 2007 119
weight = 150
while weight < 200 do
puts "Weight: " + weight.to_s
weight += 5
end
July 23, 2007 120
weight = 150
until weight == 200 do
puts "Weight: " + weight.to_s
weight += 5
end
July 23, 2007 121
weight = 150
begin
puts "Weight: " + weight.to_s
weight += 5
end until weight == 200
July 23, 2007 122
Statement modifier for until
July 23, 2007 123
puts age += 1 until age > 28
July 23, 2007 124
case
July 23, 2007 125
lang = :de
dog = case lang when :en: "dog" when :es: "perro" when :fr: "chien" when :de: "Hund" else "dog"end
July 23, 2007 126
With ranges
July 23, 2007 127
scale = 8case scale when 0: puts "lowest" when 1..3: puts "medium-low" when 4..5: puts "medium" when 6..7: puts "medium-high" when 8..9: puts "high" when 10: puts "highest" else puts "off scale"end
July 23, 2007 128
Ternary operator
July 23, 2007 129
def two_plus( one, two, *args ) length = args.size label = length == 1 ? " variable argument" : " variable arguments"
num = length.to_s + label + " (" + args.inspect + ")"
numend
puts two_plus( 1, 2 )
July 23, 2007 130
for loop
July 23, 2007 131
for i in 1..10 do print i, " " end
# => 1 2 3 4 5 6 7 8 9 10
July 23, 2007 132
upto method
July 23, 2007 133
1.upto(10) { |i| print i, " " }
July 23, 2007 134
downto mehtod
July 23, 2007 135
10.downto(1) {|i| print i," " }
July 23, 2007 136
Classes
• Almost everything is an object• Instance variables and methods• Class variables and methods• Single inheritance only• Classes are open, even built-in
classes
July 23, 2007 137
class Hello
def initialize( name )
@name = name
end
def hi
puts "Hello, "+@name+"!"
end
end
July 23, 2007 138
hello = Hello.new( "Matz!" )
hello.hi
July 23, 2007 139
Modules
• Module hold method definitions, etc.• You cannot instantiate modules• But you can include (mixin) modules• Methods, etc., are implemented in
modules but never available until mixed in
• Bridge between single and multiple inheritance