ruby-acm
DESCRIPTION
Ruby Tutorial SlidesTRANSCRIPT
-
Introducing Ruby
a guide for beginners by
David A. Blackauthor, The Well-Grounded Rubyist
Spring 2011
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
2
Topic overviewIdentifiersVariablesConstantsKeywordsOperatorsLiteral object constructorsConditionals and case statementsObject basicsMethods and messagesObject-specific methodsInstance variables and attributesModulesClassesInheritanceself (default object)Built-in classes:
Array, String, Hash,Range, Regexp, File, numerics,times, dates
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
3
Ruby Created by Yukihiro "Matz" Matsumoto Version 1.0: 1996 Object-oriented Interpreted Optimized for programmer productivity Untyped variables Highly dynamic Major influences: Lisp, Smalltalk, CLOS, Perl
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
4
View from outer space
Programs organized as classes and modules Classes and modules contain method
definitions and constants Classes spawn instances Modules allow for flexible composition of
complex behaviors Ruby also supports "top-level" code (outside
of class/module definitions)
-
Identifiers
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
6
Ruby identifiers
Variables Constants Method names Keywords
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
7
Variables
Local a = 1str = "Hello"
Instance @name = "David" Global $VERBOSE = true Class @@x = 1
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
8
Variable naming rules
Local: start with a-z or _ consist of A-Za-z0-9_
Instance: start with @ consist of A-Za-z0-9_
Global start with $ can include other punctuation ($? etc.)
Class start with @@ consist of A-Za-z0-9_
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
9
Constants
Constants start with an uppercase letter They are defined inside classes and
modules They are not exactly constant!
but you get warned if you redefine them
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
10
Constants
RUBY_VERSION Holds any value
String Name of a class
Math Name of a module
Math::PI Nested in a module
class Automobile Your classes and modules
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
11
Method names
puts "Hello" puts is a methoddef update_info define a method"Hello".reverse call the "reverse"
method on a string
Integer("123") Uppercase method name(unusual, but some exist)
Method names are similar to local variable names, except that they canstart with an uppercase letter.
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
12
Keywords
if, unless, when, case, def, class, module, super, yield, and more!
Can't be used as local variables:
if = 1 error!
-
Basic constructs
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
14
Literals and expressions
"Good morning, Mr. Phelps." # literal string
["Ruby", "Perl", "C"] # literal array (of strings)
{ "NY" => "New York", "CT" => "Connecticut", "NJ" => "New Jersey" } # literal hash ("dictionary")
/^[a-z]+$/ # literal regular expression
(0...100) # literal range
a = 10 # variable assignmentb = a + 5 # object reference via the variable
"Good morning".upcase # method call
Many Ruby objects can be created with literal constructors,like quotation marks for strings. You'll see and use all of thesefrequently.
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
15
Operators
Assignment (=) Arithmetic (+ - * / % **) Shortcut arithmetic (+= *= etc.) Boolean (|| &&) Short-circuit Boolean (||= &&=) Bitwise (^ | &)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
16
Operators that are methods
Many "operators" are actually methods!
2 + 3 is really 2.+(3)2 * 3 is really 2.*(3)16 | 2 is really 16.|(2)
Makes for easy "operator" overloading (via method definitions)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
17
Conditionals
if x == 1 puts "x is 1"elsif x == 2 puts "x is 2"else puts "x is something other than 1 or 2"end
puts "x is not 3" unless x == 3
if/elsif/.../else/end Negative conditionals with unless End-of-line modifier form accepted
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
18
Case statementscase/when/.../else/endFirst match "wins"Cases can be combined
case xwhen 1 puts "x is 1"when 2, 3 puts "x is 2 or 3"else puts "x is not 1, 2, or 3"end
-
Objects, messages, and methods
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
20
Object overview
Ruby instructions consists mainly of messages being sent to objects.
Objects are programmable constructs with storage and calculation capabilities
Every expression evaluates to an object Every object is an instance of a class
and classes are also objects (but don't worry about that now!)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
21
Object derivation
Objects are represented by literal constructors, such as "Hi!" for a
string identifiers (variables and constants) that
have been assigned to complex expressions or calculations
every statement or expression reduces to a single object
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
22
Sending objects messages
A message is sent to an object with the dot operator:string = "Hi".upcase # "HI"low = string.downcase # "hi"
or indirectly with send:method_name = "upcase"string = "Hi".send(method_name) # "HI"
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
23
Messages and methods
Objects receive messages Messages are resolved (if possible) into
method names Every method is defined in a class or
module The object looks for the method along a
method search path, consisting of classes and modules
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
24
How does an object know about a method?
An object's methods include: singleton methods (those defined just for
this object) instance methods defined in modules with
which the object has been extended instance methods defined in the object's
class, and in that class's ancestral classes and modules
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
25
Three ways to teach an object
module ShoutCapable def shout self.upcase + "!!!" endend
string = "Hello"string.extend(ShoutCapable)
class String include ShoutCapableend
string = "Hello"
string = "Hello"
def string.shout self.upcase + "!!!"end
puts string.shout HELLO!!!
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
26
Three ways to teach an objectstring = "Hello"
def string.shout self.upcase + "!!!"end
puts string.shout HELLO!!!
"Singleton" method definition. Applies to this object only.No other string can shout!
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
27
Three ways to teach an object
module ShoutCapable def shout self.upcase + "!!!" endend
string = "Hello"string.extend(ShoutCapable)
puts string.shout HELLO!!!
Put the method in a module and extend the objectwith the module. The object "learns" all the methodsdefined in the module.
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
28
Three ways to teach an objectclass String include ShoutCapableend
string = "Hello"
puts string.shout HELLO!!!
Class-wide: include the module in the class. Now allstrings will be about to shout! (See previous slides for themodule code.)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
29
Singleton methods
Defined directly on an objectdef string.shout
Only for this object (with one special case, to be examined later)
Represents Ruby objects at their most dynamic!
Not an everyday technique, but has some important use-cases
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
30
Modules
Defined using the module keyword Bundles of methods Also handy for name-spacing Can also store constants
and nested modules Can be "attached" to individual objects, via extend
Can be "attached" to entire classes, via include
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
31
Classes
A specialization of modules Also a bundle of methods and constants
(and nested classes, modules, constants...) but classes can also create new objects
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
32
Creating an instance of a class
class Person def name "David" # All people are named David for the moment! endend
d = Person.new # Create a new Person object
print "Here's the person's name: "puts d.name
Output:
Here's the person's name: David
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
33
Inheritance
Classes can have subclasses The subclass inherits from the superclass Instances of the subclass can call methods
defined in the superclass Inheritance cascades: subsubclasses, etc. Every class can have only one superclass
i.e., Ruby supports single inheritance
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
34
Inheritance syntax: > string = "Hi there."=> "Hi there.">> string.upcase=> "HI THERE."
>> string.reverse=> ".ereht iH"
>> string.upcase.reverse=> ".EREHT IH"
>> string.split=> ["Hi", "there."]
>> string.delete('e')=> "Hi thr."
>> string = " Hello again. "=> " Hello again. ">> string.strip=> "Hello again."
>> string = "greetings to you."=> "greetings to you.">> string.capitalize=> "Greetings to you."
>> string.swapcase=> "GREETINGS TO YOU."
>> string = "abc"=> "abc">> string.succ=> "abd"
>> string = "Ends with newline\n"=> "Ends with newline\n">> string.chomp=> "Ends with newline"
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
64
Arrays
Ordered collections Literal constructor: [] Indexed by number
zero-originarray = ["apple", "orange", "pear"]puts array[1] # orange
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
65
Some common array methods
colors = ["red", "orange", "yellow"]
colors[2] # "yellow"colors.reverse # ["yellow", "orange", "red"]colors.push("green") # ["red", "orange", "yellow", "green"] colors.pop # returns "green", which is no longer # in the array colors.sort # ["orange", "red", "yellow"]
more_colors = ["green", "blue"]five_colors = colors + more_colors # creates new arraycolors.concat(more_colors) # adds "green" and "blue" to colors
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
66
Hashes
Unordered, keyed collections "dictionary", "associative array" In 1.9: ordered by order of key
insertion Literal constructor: {} Key/value separator: => Values retrieved by key
states = {"New York" => "NY", "New Jersey" => "NJ", "Texas" => "TX" }
puts states["New Jersey"] # "NJ"
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
67
Some common hash methods
states.has_key?("New York") # truestates["Oregon"] # nilstates.fetch("Oregon") # fatal error!
states.delete("New York") # removes pair from hash
more_states = {"Virginia" => "VA" }states.merge(more_states) # new hash, with all pairsstates.update(more_states) # adds VA to states
-
Iterators
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
69
Fibonacci iterator
def fibit n,m = 1,1 loop do yield n n,m = m,n+m endend
fibit do |num| puts "Next: #{num}" break if num > 100end
Next: 1Next: 1Next: 2Next: 3Next: 5Next: 8Next: 13Next: 21Next: 34Next: 55Next: 89Next: 144
The method The method call
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
70
Iteration mechanics
def fibit n,m = 1,1 loop do yield n n,m = m,n+m endend
fibit do |num| puts "Next: #{num}" break if num > 100end
Next: 1Next: 1Next: 2Next: 3Next: 5Next: 8Next: 13Next: 21Next: 34Next: 55Next: 89Next: 144
1 1 2 3 5 ... 89144
The iterating methodyields one or morevalues.
The method call includesa code block. Each yieldedvalue is bound, in turn, to the block parameter (num)for one execution of theblock.
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
71
Iteration semantics
The iterator (the method that iterates) yields values to the code block
The code block can take arguments, bound to parameters (between vertical pipes)
The code block returns a value, which is the value of the call to yield
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
72
Returning a value from the blockclass Guesser def guess(limit = 10) g = rand(limit) + 1 outcome = yield(g) if outcome puts "#{g} was right!" else puts "No, #{g} was wrong" end endend
guesser = Guesser.newguesser.guess do |g| g == 3end
Get a random number between 1and limit (default limit: 10). Yield that number to the code block,and save the result.
Did the block return a true value?If so, you win; otherwise, you lose.
When you use the Guesser class, you supplywhatever "win/lose" logic you want, inside the block.In this example, you win if the random number yielded from the guess method is 3, because in thatcase, the block returns true.
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
73
Collection iteration
Very common for arrays and hashes Basic iterator: each
[1,2,3,4,5].each do |x| puts "Next number is #{x}!"endNext number is 1!Next number is 2!Next number is 3!Next number is 4!Next number is 5!
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
74
Methods based on each
each is the generic enumerator call the block once for each element
The Enumerable module defines iterator methods based on each select, find, inject, reject, map, etc. These are all defined in terms of each.
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
75
map
array = [1,2,3,4,5]new_array = array.map {|x| x * 10 }p new_array [10,20,30,40,50]
hash = { "NY" => "New York", "CT" => "Connecticut", "NJ" => "New Jersey" }state_list = hash.map do |abbr, state| "#{state} is abbreviated #{abbr}"endp state_list
["New York is abbreviated NY", "New Jersey is abbreviated NJ", "Connecticut is abbreviated CT"]
map performs atransformation,calling the codeblock once for eachelement in the originalcollection, and returningan array consisting ofthe results of all of thecalls to the block.
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
76
select
array = [1,2,3,4,5]big = array.select {|x| x > 3 }p big
[4,5]
hash = { "NY" => "New York", "CT" => "Connecticut", "NJ" => "New Jersey" }big_names = hash.select {|abbr, state| state.split.size > 1 }p big_names
[["NY", "New York"], ["NJ", "New Jersey"]]
select returns anarray of all theelements of thecollection forwhich calling theblock returns atrue value.
(reject does theopposite.)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
77
Ranges
Ranges test for inclusion Ranges can behave like collections
if they are made up of discrete, countable units
Ranges can involve numbers, strings, anything that has a "succ" method
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
78
Range instantiation
r = 1..10 # inclusive range, 1 through 10r = 1...10 # exclusive range, 1 through
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
79
Range inclusion tests
(1..10).include?(3) # true(1..10).include?(11) # false(1...10).include?(3) # true(1...10).include?(10) # false(1..10).include?(3.141) # true
('a'..'z').include?('g') # true('a'..'z').include?('word') # true
Inclusion tests look for >= and
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
80
Ranges as collections
(1..10).to_a # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10](1..10).map {|e| e * 10 } # [10,20,30,40,50,60,70,80,90,100]array = [*1..10] # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(1.1..10.0).to_a # Error: can't iterate from float(1..10.1).to_a # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
('a'..'e').to_a # ["a", "b", "c", "d", "e"]('a'..'e').include?('black') # true
Even though the range includes 'black', 'black' is not oneof the members of its collection. (This changes in 1.9, wherethere's a difference between include? and cover? 'a'..'e' is saidto cover, but not include, 'black'.)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
81
Regular expressions
Literals constructed with // Anchors:
Beginning of string: \A End of string: \z End of string, minus newline: \Z Beginning of line: ^ End of line: $
Modifiers: Include \n in . : /m Ignore unescaped whitespace: /x No /g (global modifier): use gsub or scan
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
82
Using regexes: match>> s = "Good morning. I am a string."=> "Good morning. I am a string.">> m = /mor/.match(s)=> # # match returns a MatchData object>> m.string # which knows its string=> "Good morning. I am a string.">> m[0] # and its match=> mor">> m.pre_match # and other data=> "Good ">> m.post_match=> "ning. I am a string.">> m = /Good (morning). (I)/.match(s) # parenthetical captures=> #>> m.captures # available via #captures, or=> ["morning", "I"]>> m.to_a=> ["Good morning. I", "morning", "I"]>> m[1] # array-style, or=> "morning">> $1=> morning" # magic global variables
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
83
Using regexes: =~
>> str = "I am a string"=> "I am a string">> str =~ /am/ # returns offset of match=> 2>> str =~ /hello/ # or nil if no match=> nil
Faster than Regexp#match Sets global MatchData object $~ Sets global captures variables ($1, $2, etc.)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
84
Using regexes: scan
Use scan for global matching>> string = "This is his wish."=> "This is his wish.">> array = string.scan(/is/)=> ["is", "is", "is", "is"]>> array = string.scan(/(.)(is)/)=> [["h", "is"], [" ", "is"], ["h", "is"], ["w", "is"]]>> string.scan(/is/) {|match| puts "Found: #{match}" }Found: isFound: isFound: isFound: is>> string.scan(/(.)(is)/) {|captures| puts "Captures: #{captures.inspect}" }Captures: ["h", "is"]Captures: [" ", "is"]Captures: ["h", "is"]Captures: ["w", "is"]
With captures, one sub-array per scan
Block called once per scan
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
85
Using regexes: sub and gsub>> string = "The rain in Spain"=> "The rain in Spain">> string.sub(/in/, "IN")=> "The raIN in Spain">> string.gsub(/in/, "IN")=> "The raIN IN SpaIN">> string.sub!(/in/, "IN")=> "The raIN in Spain">> string=> "The raIN in Spain">> string.gsub!(/in/, "IN")=> "The raIN IN SpaIN">> string=> "The raIN IN SpaIN">> string.gsub(/IN/) {|match| match.reverse }=> "The raNI NI SpaNI">> string.gsub(/(a)I/) {|e| $1.upcase }=> "The rAN IN SpAN">> string.gsub(/(a)I/, '\1!')=> "The ra!N IN Spa!N"
sub does one replacementgsub does all
sub! and gsub! permanentlychange the string
The code block receivesthe matched substring, andhas access to the $n capturevariables
The replacement string canget the captures via escapednumbers (\1, \2, etc.)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
86
Numerics
Numbers are objects! Integer (Fixnum/Bignum) Float In standard library:
Complex, Rational, BigDecimal
Infix operators are methods e.g., 3 + 2 is really 3.+(2)
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
87
Numeric methods
upto/downto/step3.upto(6) {|x| puts x * 10 }10.downto(1) {|x| puts -x + 10 }1.step(100,10) {|x| puts x }
divmod10.divmod(3) # [3,1]
abs (absolute value) floor, ceil, round, truncate
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
88
Floats
Instances of Float "Wrapper"-style instances>> 10.1.object_id=> -604737798>> 10.1.object_id=> -604416838
Subject to the universal precision issues
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
89
Time/date objects
Time, Date, DateTime classes Spread over several libraries:
you may have to "require 'time'" and/or "require 'date'"
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
90
Time/date examples
=> Mon Nov 10 10:17:14 UTC 2008>> t = Time.now=> Mon Nov 10 05:17:31 -0500 2008>> t + 2000 # add seconds=> Mon Nov 10 05:50:51 -0500 2008>> t.day # likewise month, year, hour, min,
sec=> 10>> t.strftime("%y/%m/%d") # wraps strftime(3)=> "08/11/10">> t.utc? # UTC?=> false>> t.zone # timezone=> "EST"
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
91
Date/DateTime
>> d = Date.today=> #>> puts d2008-11-10>> puts d + 1 # +/- days2008-11-11>> puts d >> 1 # >>/> puts d.julian # also gregorian2008-10-28
>> dt = DateTime.now=> #>> puts dt2008-11-10T05:25:54-05:00=> nil>> puts dt + 12008-11-11T05:25:54-05:00=> nil>> puts dt >> 12008-12-10T05:25:54-05:00
-
ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC
92
File reading and writingRead in fle content as a string:str = File.read("filename")
Read in a fle as an array of lines: array = File.readlines("filename")
Open a fle for output: f = File.open("filename", "w")
Write to fle: f.puts("A line for the file")
Close fle: f.close
Use block to automate closing of flehandle: File.open("filename","w") do |f| f.puts("A line for the file") end
Iterate through lines of a fle: File.open("filename") do |f| f.each {|line| puts line.reverse } end
PowerPoint PresentationTopic overviewRubyView from outer spaceIdentifiersRuby identifiersVariablesVariable naming rulesConstantsSlide 10Method namesKeywordsBasic constructsLiterals and expressionsOperatorsOperators that are methodsConditionalsCase statementsObjects, messages, and methodsObject overviewObject derivationSending objects messagesMessages and methodsHow does an object know about a method?Three ways to teach an objectSlide 26Slide 27Slide 28Singleton methodsModulesClassesCreating an instance of a classInheritanceInheritance syntax: