Index by each word
   A quick Ruby Tutorial, Part 3
                                                          class WordIndex
                                                           def initialize
                                                            @index = {}
                                                           end
                                                           def add_to_index(obj, *phrases)
                                                             phrases.each do |phrase|
                                                              phrase.scan(/w[-w']+/) do |word| # extract each word
                                                               word.downcase!
               COMP313                                         @index[word] = [] if @index[word].nil?
                                                               @index[word].push(obj)
Source: Programming Ruby, The Pragmatic                        end
                                                              end
Programmers’ Guide by Dave Thomas, Chad                     end
                                                           def lookup(word)
          Fowler, and Andy Hunt                              @index[word.downcase]
                                                           end
                                                          end




        Add full index to SongList                                                          Ranges
 class SongList                                           1..10
  def initialize                                          'a'..'z'
    @songs = Array.new                                    my_array = [ 1, 2, 3 ]
    @index = WordIndex.new                                0...my_array.length
  end
  def append(song)                                        (1..10).to_a       [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    @songs.push(song)                                     ('bar'..'bat').to_a     ["bar", "bas", "bat"]
    @index.add_to_index(song, song.name, song.artist)
    self                                                  digits = 0..9
  end                                                     digits.include?(5)        true
  def lookup(word)                                        digits.min      0
    @index.lookup(word)                                   digits.max       9
  end                                                     digits.reject {|i| i < 5 }     [5, 6, 7, 8, 9]
 end                                                      digits.each {|digit| dial(digit) }      0..9




      Range example: VU meter
 class VU
                                                             VU Ranges / Ranges in conditions
  include Comparable
  attr :volume
  def initialize(volume) # 0..9                           medium_volume = VU.new(4)..VU.new(7)
    @volume = volume                                      medium_volume.to_a    [####, #####, ######, #######]
  end
                                                          medium_volume.include?(VU.new(3))    false
  def inspect
    '#' * @volume
  end                                                     (1..10) === 5      true
  # Support for ranges
                                                          (1..10) === 15       false
  def <=>(other)
    self.volume <=> other.volume                          (1..10) === 3.14159        true
  end                                                     ('a'..'j') === 'c'  true
  def succ
    raise(IndexError, "Volume too big") if @volume >= 9
                                                          ('a'..'j') === 'z'  false
    VU.new(@volume.succ)
  end
 end




                                                                                                                       1
Regular expressions                                                  Special vars $` $& $’
a = Regexp.new('^s*[a-z]')       /^s*[a-z]/                          def show_regexp(a, re)
                                                                        if a =~ re
b = /^s*[a-z]/   /^s*[a-z]/
                                                                          "#{$`}<<#{$&}>>#{$'}"
c = %r{^s*[a-z]}     /^s*[a-z]/                                       else
                                                                          "no match"
                                                                        end
                                                                       end
name = "Fats Waller"
name =~ /a/   1                                                        show_regexp('very interesting', /t/)    very in<<t>>eresting
                                                                       show_regexp('Fats Waller', /a/)      F<<a>>ts Waller
name =~ /z/   nil
                                                                       show_regexp('Fats Waller', /ll/)     Fats Wa<<ll>>er
/a/ =~ name   1                                                        show_regexp('Fats Waller', /z/)      no match




          Special chars, anchors                                                          More RegExps
., |, (, ), [, ], {, }, +, , ^, $, *, and ?                           show_regexp('Price $12.', /[aeiou]/)      Pr<<i>>ce $12.
                                                                       show_regexp('Price $12.', /[s]/)     Price<< >>$12.
show_regexp('kangaroo', /angar/)               k<<angar>>oo            show_regexp('Price $12.', /[[:digit:]]/)   Price $<<1>>2.
                                                                       show_regexp('Price $12.', /[[:space:]]/)     Price<< >>$12.
show_regexp('!@%&-_=+', /%&/)                  !@<<%&>>-_=+
                                                                       show_regexp('Price $12.', /[[:punct:]aeiou]/)     Pr<<i>>ce $12.

show_regexp("this isnthe time", /^the/)     this isn<<the>> time
                                                                       a = 'see [Design Patterns-page 123]'
show_regexp("this isnthe time", /is$/)    this <<is>>nthe time       show_regexp(a, /[A-F]/)     see [<<D>>esign Patterns-page 123]
show_regexp("this isnthe time", /Athis/)     <<this>> isnthe time   show_regexp(a, /[A-Fa-f]/)    s<<e>>e [Design Patterns-page 123]
 show_regexp("this isnthe time", /Athe/) no match                    show_regexp(a, /[0-9]/)    see [Design Patterns-page <<1>>23]
                                                                       show_regexp(a, /[0-9][0-9]/)   see [Design Patterns-page <<12>>3]




                  character classes                                                             Repetition
d [0-9] Digit character                                               r* matches zero or more occurrences of r.
D [^0-9] Any character except a digit                                 r+ matches one or more occurrences of r.
s [ trnf] Whitespace character                                    r? matches zero or one occurrence of r.
S [^ trnf] Any character except whitespace                        r{m,n} matches at least m and at most n occurrences of r.
w [A-Za-z0-9_] Word character                                         r{m,} matches at least m occurrences of r.
W [^A-Za-z0-9_] Any character except a word character                 r{m} matches exactly m occurrences of r.

                                                                       /ab+/     matches ab, abb, abbbb, …
                                                                       /(ab)+/   matches ab, abab, ababab, …
                                                                       /a*/      matches everything (why?)




                                                                                                                                           2
Greedy matching/Alternatives                                                              Groupings
a = "The moon is made of cheese"                                   show_regexp('banana', /an*/)   b<<an>>ana
show_regexp(a, /w+/)    <<The>> moon is made of cheese            show_regexp('banana', /(an)*/)  <<>>banana
show_regexp(a, /s.*s/)  The<< moon is made of >>cheese           show_regexp('banana', /(an)+/)   b<<anan>>a

show_regexp(a, /s.*?s/)   The<< moon >>is made of cheese
                                                                   a = 'red ball blue sky'
show_regexp(a, /[aeiou]{2,99}/)  The m<<oo>>n is made of
                                                                   show_regexp(a, /blue|red/)    <<red>> ball blue sky
   cheese
                                                                   show_regexp(a, /(blue|red) w+/)    <<red ball>> blue sky
                                                                   show_regexp(a, /(red|blue) w+/)    <<red ball>> blue sky
a = "red ball blue sky"
                                                                   show_regexp(a, /red|blue w+/)    <<red>> ball blue sky
show_regexp(a, /d|e/)        r<<e>>d ball blue sky                 show_regexp(a, /red (ball|angry) sky/)   no match a = 'the red angry sky'
show_regexp(a, /al|lu/)   red b<<al>>l blue sky                    show_regexp(a, /red (ball|angry) sky/)   the <<red angry sky>>
show_regexp(a, /red ball|angry sky/)   <<red ball>> blue sky




     Groupings collect matches                                              Match inside with 1,…
"12:50am" =~ /(dd):(dd)(..)/   0                               # match duplicated letter
"Hour is #$1, minute #$2"       "Hour is 12, minute 50"            show_regexp('He said "Hello"', /(w)1/)        He said "He<<ll>>o"
                                                                   # match duplicated substrings
"12:50am" =~ /((dd):(dd))(..)/ 0                               show_regexp('Mississippi', /(w+)1/)       M<<ississ>>ippi
"Time is #$1"    "Time is 12:50"
"Hour is #$2, minute #$3"
"Hour is 12, minute 50"                                            show_regexp('He said "Hello"', /(["']).*?1/)     He said <<"Hello">>
"AM/PM is #$4"     "AM/PM is am"                                   show_regexp("He said 'Hello'", /(["']).*?1/)     He said <<'Hello'>>




              Substitute patterns                                           Upcase every first char
a = "the quick brown fox"                                          def mixed_case(name)
a.sub(/[aeiou]/, '*')     "th* quick brown fox"                     name.gsub(/bw/) {|word| word.upcase }
a.gsub(/[aeiou]/, '*')      "th* q**ck br*wn f*x"                  end
a.sub(/sS+/, '')     "the brown fox"
a.gsub(/sS+/, '')     "the"                                      mixed_case("fats waller")  "Fats Waller"
                                                                   mixed_case("louis armstrong")   "Louis Armstrong"
a.sub(/^./) {|match| match.upcase }   "The quick brown fox"        mixed_case("strength in numbers")   "Strength In Numbers"
a.gsub(/[aeiou]/) {|vowel| vowel.upcase }  "thE qUIck brOwn fOx"




                                                                                                                                               3
Classes behind regexps                                      optional args for methods
re = /(d+):(d+)/ # match a time hh:mm                    def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach")
re.class -> Regexp                                          "#{arg1}, #{arg2}, #{arg3}."
md = re.match("Time: 12:34am")                             end
md.class   MatchData
md[0]    "12:34"              # $&                         cool_dude   "Miles, Coltrane, Roach."
md[1]    "12"                 # $1                         cool_dude("Bart")    "Bart, Coltrane, Roach."
md[2]    "34"                 # $2                         cool_dude("Bart", "Elwood")     "Bart, Elwood, Roach."
md.pre_match     "Time: ”     # $`                         cool_dude("Bart", "Elwood", "Linus")     "Bart, Elwood, Linus."
md.post_match     "am"        # $’




       Variable number of args                                            code blocks again
def varargs(arg1, *rest)                                   def take_block(p1)
 "Got #{arg1} and #{rest.join(', ')}"                       if block_given?
end                                                           yield(p1)
                                                            else
varargs("one")    "Got one and "                             p1
varargs("one", "two")     "Got one and two"                 end
varargs "one", "two", "three"   "Got one and two, three"   end

                                                           take_block("no block")     "no block"
                                                           take_block("no block") {|s| s.sub(/no /, ‘’) }   "block"




         Capture block explicitly                                          Calling a method
class TaxCalculator                                        connection.download_MP3("jitterbug") {|p| show_progress(p) }
 def initialize(name, &block)
   @name, @block = name, block                             File.size("testfile") 66
 end                                                       Math.sin(Math::PI/4)    0.707106781186548
 def get_tax(amount)
   "#@name on #{amount} = #{ @block.call(amount) }"
                                                           self.class    Object
 end
                                                           self.frozen?    false
end
                                                           frozen?     false
tc = TaxCalculator.new("Sales tax") {|amt| amt * 0.075 }   self.object_id    969948
tc.get_tax(100)    "Sales tax on 100 = 7.5"                object_id     969948
tc.get_tax(250)    "Sales tax on 250 = 18.75"




                                                                                                                             4
Multiple return values                            Expanding arrays into args
def some_method                                           def five(a, b, c, d, e)
 100.times do |num|                                        "I was passed #{a} #{b} #{c} #{d} #{e}"
  square = num*num                                        end
  return num, square if square > 1000
 end
                                                          five(1, 2, 3, 4, 5 )       "I was passed 1 2 3 4 5"
end
                                                          five(1, 2, 3, *['a', 'b'])      "I was passed 1 2 3 a b"
                                                          five(*(10..14).to_a)          "I was passed 10 11 12 13 14"
some_method           [32, 1024]

num, square = some_method
num    32
square    1024




         & for procedure objects                                 Keyword args: use Hash
print "(t)imes or (p)lus: "                               class SongList
times = gets                                               def create_search(name, params)
print "number: "
                                                             # ...
number = Integer(gets)
if times =~ /^t/                                           end
  calc = lambda {|n| n*number }                           end
else
  calc = lambda {|n| n+number }
                                                          list.create_search("short jazz songs", { 'genre' => "jazz",
end
                                                              'duration_less_than' => 270 })
puts((1..10).collect(&calc).join(", "))

(t)imes or (p)lus: t                                      list.create_search('short jazz songs', 'genre' => 'jazz',
number: 2                                                     'duration_less_than' => 270)
2, 4, 6, 8, 10, 12, 14, 16, 18, 20




                     Expression fun                                      More expressions
a=b=c=0              0                                    rating = case votes_cast
[ 3, 1, 7, 0 ].sort.reverse     [7, 3, 1, 0]                       when 0...10 then Rating::SkipThisOne
song_type = if song.mp3_type == MP3::Jazz                          when 10...50 then Rating::CouldDoBetter
                 if song.written < Date.new(1935, 1, 1)            else Rating::Rave
                    Song::TradJazz                                 end
                 else
                    Song::Jazz
                 end                                      command expressions:
                else                                      `date` "Mon Jan 16 22:32:17 CST 2006n"
                 Song::Other
                end




                                                                                                                        5

More Related Content

PPSX
Awk essentials
PDF
Perl intro
PDF
Perl 5.10 for People Who Aren't Totally Insane
DOCX
Awk programming
PPTX
Unit 1-array,lists and hashes
PPTX
String variable in php
PPT
Learning sed and awk
PDF
Perl Scripting
Awk essentials
Perl intro
Perl 5.10 for People Who Aren't Totally Insane
Awk programming
Unit 1-array,lists and hashes
String variable in php
Learning sed and awk
Perl Scripting

What's hot (19)

KEY
Introduction to Perl Best Practices
PDF
Improving Dev Assistant
PDF
Perl programming language
PPT
Perl Presentation
PPTX
PHP Strings and Patterns
ODP
Introduction to Perl - Day 1
PPT
Bioinformatica 06-10-2011-p2 introduction
ODP
Intermediate Perl
PPT
LPW: Beginners Perl
ODP
Introduction to Perl
PDF
ruby1_6up
PPSX
Sed tips and_tricks
PDF
Hadoop Pig
ODP
Introduction to Perl - Day 2
PPTX
Licão 13 functions
Introduction to Perl Best Practices
Improving Dev Assistant
Perl programming language
Perl Presentation
PHP Strings and Patterns
Introduction to Perl - Day 1
Bioinformatica 06-10-2011-p2 introduction
Intermediate Perl
LPW: Beginners Perl
Introduction to Perl
ruby1_6up
Sed tips and_tricks
Hadoop Pig
Introduction to Perl - Day 2
Licão 13 functions
Ad

Viewers also liked (18)

PPTX
Agile - User Stories
PDF
Chelysheva_E_poster presentation_EAFO
PDF
INLS890_ProjectPlan
ODT
Evolución historica de la economia en guatemala
PPTX
La Regione Lazio per la re-industrializzazione
PPSX
Animals 1 primaria
PPT
Transformers Episode 19 Rescue Part 1
PPTX
SFUSGS
PPT
1 8 Landscape Business Taxes & Licenses
PPTX
Evaluating Network and Security Devices
PPTX
28 4 Echinoderms
PDF
Promo Shops Promotional And Marketing Services
DOC
Triumph Over Time Dr Shriniwas Janardan Kashalikar
PDF
InTechnology InSpire Newsletter - Issue 4
PPS
Asturias Vistas 14
PPS
1 George
PPTX
How cowpat rots?
PDF
2008 Airlines and Advocacy
Agile - User Stories
Chelysheva_E_poster presentation_EAFO
INLS890_ProjectPlan
Evolución historica de la economia en guatemala
La Regione Lazio per la re-industrializzazione
Animals 1 primaria
Transformers Episode 19 Rescue Part 1
SFUSGS
1 8 Landscape Business Taxes & Licenses
Evaluating Network and Security Devices
28 4 Echinoderms
Promo Shops Promotional And Marketing Services
Triumph Over Time Dr Shriniwas Janardan Kashalikar
InTechnology InSpire Newsletter - Issue 4
Asturias Vistas 14
1 George
How cowpat rots?
2008 Airlines and Advocacy
Ad

Similar to ruby3_6up (20)

PDF
ruby1_6up
PDF
Regexp secrets
PDF
Be aware of side effects
PDF
Hw1 rubycalisthenics
PDF
Ruby 程式語言入門導覽
PDF
this is ruby test
PDF
Pdf sample3
KEY
Regular expressions
PDF
And now you have two problems. Ruby regular expressions for fun and profit by...
KEY
Strings and Symbols
PDF
Ruby presentasjon på NTNU 22 april 2009
PDF
Ruby presentasjon på NTNU 22 april 2009
PDF
Ruby presentasjon på NTNU 22 april 2009
PDF
Ruby Language - A quick tour
PDF
PDF
Ruby on Rails Presentation
PPTX
Ruby introduction part1
ZIP
Advanced Regular Expressions Redux
PDF
Ruby On Rails Cheat Sheet
PDF
Eloquent ruby
ruby1_6up
Regexp secrets
Be aware of side effects
Hw1 rubycalisthenics
Ruby 程式語言入門導覽
this is ruby test
Pdf sample3
Regular expressions
And now you have two problems. Ruby regular expressions for fun and profit by...
Strings and Symbols
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
Ruby Language - A quick tour
Ruby on Rails Presentation
Ruby introduction part1
Advanced Regular Expressions Redux
Ruby On Rails Cheat Sheet
Eloquent ruby

More from tutorialsruby (20)

PDF
&lt;img src="../i/r_14.png" />
PDF
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
PDF
&lt;img src="../i/r_14.png" />
PDF
&lt;img src="../i/r_14.png" />
PDF
Standardization and Knowledge Transfer – INS0
PDF
xhtml_basics
PDF
xhtml_basics
PDF
xhtml-documentation
PDF
xhtml-documentation
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
HowTo_CSS
PDF
HowTo_CSS
PDF
BloggingWithStyle_2008
PDF
BloggingWithStyle_2008
PDF
cascadingstylesheets
PDF
cascadingstylesheets
&lt;img src="../i/r_14.png" />
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
Standardization and Knowledge Transfer – INS0
xhtml_basics
xhtml_basics
xhtml-documentation
xhtml-documentation
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
HowTo_CSS
HowTo_CSS
BloggingWithStyle_2008
BloggingWithStyle_2008
cascadingstylesheets
cascadingstylesheets

Recently uploaded (20)

PPTX
Benefits of Physical activity for teenagers.pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPT
Geologic Time for studying geology for geologist
PPTX
Chapter 5: Probability Theory and Statistics
PPT
What is a Computer? Input Devices /output devices
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Getting Started with Data Integration: FME Form 101
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Zenith AI: Advanced Artificial Intelligence
PPTX
Web Crawler for Trend Tracking Gen Z Insights.pptx
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
A review of recent deep learning applications in wood surface defect identifi...
DOCX
search engine optimization ppt fir known well about this
Benefits of Physical activity for teenagers.pptx
Hindi spoken digit analysis for native and non-native speakers
Taming the Chaos: How to Turn Unstructured Data into Decisions
sustainability-14-14877-v2.pddhzftheheeeee
Developing a website for English-speaking practice to English as a foreign la...
Assigned Numbers - 2025 - Bluetooth® Document
Geologic Time for studying geology for geologist
Chapter 5: Probability Theory and Statistics
What is a Computer? Input Devices /output devices
Module 1.ppt Iot fundamentals and Architecture
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
DP Operators-handbook-extract for the Mautical Institute
Getting Started with Data Integration: FME Form 101
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
1 - Historical Antecedents, Social Consideration.pdf
Zenith AI: Advanced Artificial Intelligence
Web Crawler for Trend Tracking Gen Z Insights.pptx
O2C Customer Invoices to Receipt V15A.pptx
A review of recent deep learning applications in wood surface defect identifi...
search engine optimization ppt fir known well about this

ruby3_6up

  • 1. Index by each word A quick Ruby Tutorial, Part 3 class WordIndex def initialize @index = {} end def add_to_index(obj, *phrases) phrases.each do |phrase| phrase.scan(/w[-w']+/) do |word| # extract each word word.downcase! COMP313 @index[word] = [] if @index[word].nil? @index[word].push(obj) Source: Programming Ruby, The Pragmatic end end Programmers’ Guide by Dave Thomas, Chad end def lookup(word) Fowler, and Andy Hunt @index[word.downcase] end end Add full index to SongList Ranges class SongList 1..10 def initialize 'a'..'z' @songs = Array.new my_array = [ 1, 2, 3 ] @index = WordIndex.new 0...my_array.length end def append(song) (1..10).to_a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @songs.push(song) ('bar'..'bat').to_a ["bar", "bas", "bat"] @index.add_to_index(song, song.name, song.artist) self digits = 0..9 end digits.include?(5) true def lookup(word) digits.min 0 @index.lookup(word) digits.max 9 end digits.reject {|i| i < 5 } [5, 6, 7, 8, 9] end digits.each {|digit| dial(digit) } 0..9 Range example: VU meter class VU VU Ranges / Ranges in conditions include Comparable attr :volume def initialize(volume) # 0..9 medium_volume = VU.new(4)..VU.new(7) @volume = volume medium_volume.to_a [####, #####, ######, #######] end medium_volume.include?(VU.new(3)) false def inspect '#' * @volume end (1..10) === 5 true # Support for ranges (1..10) === 15 false def <=>(other) self.volume <=> other.volume (1..10) === 3.14159 true end ('a'..'j') === 'c' true def succ raise(IndexError, "Volume too big") if @volume >= 9 ('a'..'j') === 'z' false VU.new(@volume.succ) end end 1
  • 2. Regular expressions Special vars $` $& $’ a = Regexp.new('^s*[a-z]') /^s*[a-z]/ def show_regexp(a, re) if a =~ re b = /^s*[a-z]/ /^s*[a-z]/ "#{$`}<<#{$&}>>#{$'}" c = %r{^s*[a-z]} /^s*[a-z]/ else "no match" end end name = "Fats Waller" name =~ /a/ 1 show_regexp('very interesting', /t/) very in<<t>>eresting show_regexp('Fats Waller', /a/) F<<a>>ts Waller name =~ /z/ nil show_regexp('Fats Waller', /ll/) Fats Wa<<ll>>er /a/ =~ name 1 show_regexp('Fats Waller', /z/) no match Special chars, anchors More RegExps ., |, (, ), [, ], {, }, +, , ^, $, *, and ? show_regexp('Price $12.', /[aeiou]/) Pr<<i>>ce $12. show_regexp('Price $12.', /[s]/) Price<< >>$12. show_regexp('kangaroo', /angar/) k<<angar>>oo show_regexp('Price $12.', /[[:digit:]]/) Price $<<1>>2. show_regexp('Price $12.', /[[:space:]]/) Price<< >>$12. show_regexp('!@%&-_=+', /%&/) !@<<%&>>-_=+ show_regexp('Price $12.', /[[:punct:]aeiou]/) Pr<<i>>ce $12. show_regexp("this isnthe time", /^the/) this isn<<the>> time a = 'see [Design Patterns-page 123]' show_regexp("this isnthe time", /is$/) this <<is>>nthe time show_regexp(a, /[A-F]/) see [<<D>>esign Patterns-page 123] show_regexp("this isnthe time", /Athis/) <<this>> isnthe time show_regexp(a, /[A-Fa-f]/) s<<e>>e [Design Patterns-page 123] show_regexp("this isnthe time", /Athe/) no match show_regexp(a, /[0-9]/) see [Design Patterns-page <<1>>23] show_regexp(a, /[0-9][0-9]/) see [Design Patterns-page <<12>>3] character classes Repetition d [0-9] Digit character r* matches zero or more occurrences of r. D [^0-9] Any character except a digit r+ matches one or more occurrences of r. s [ trnf] Whitespace character r? matches zero or one occurrence of r. S [^ trnf] Any character except whitespace r{m,n} matches at least m and at most n occurrences of r. w [A-Za-z0-9_] Word character r{m,} matches at least m occurrences of r. W [^A-Za-z0-9_] Any character except a word character r{m} matches exactly m occurrences of r. /ab+/ matches ab, abb, abbbb, … /(ab)+/ matches ab, abab, ababab, … /a*/ matches everything (why?) 2
  • 3. Greedy matching/Alternatives Groupings a = "The moon is made of cheese" show_regexp('banana', /an*/) b<<an>>ana show_regexp(a, /w+/) <<The>> moon is made of cheese show_regexp('banana', /(an)*/) <<>>banana show_regexp(a, /s.*s/) The<< moon is made of >>cheese show_regexp('banana', /(an)+/) b<<anan>>a show_regexp(a, /s.*?s/) The<< moon >>is made of cheese a = 'red ball blue sky' show_regexp(a, /[aeiou]{2,99}/) The m<<oo>>n is made of show_regexp(a, /blue|red/) <<red>> ball blue sky cheese show_regexp(a, /(blue|red) w+/) <<red ball>> blue sky show_regexp(a, /(red|blue) w+/) <<red ball>> blue sky a = "red ball blue sky" show_regexp(a, /red|blue w+/) <<red>> ball blue sky show_regexp(a, /d|e/) r<<e>>d ball blue sky show_regexp(a, /red (ball|angry) sky/) no match a = 'the red angry sky' show_regexp(a, /al|lu/) red b<<al>>l blue sky show_regexp(a, /red (ball|angry) sky/) the <<red angry sky>> show_regexp(a, /red ball|angry sky/) <<red ball>> blue sky Groupings collect matches Match inside with 1,… "12:50am" =~ /(dd):(dd)(..)/ 0 # match duplicated letter "Hour is #$1, minute #$2" "Hour is 12, minute 50" show_regexp('He said "Hello"', /(w)1/) He said "He<<ll>>o" # match duplicated substrings "12:50am" =~ /((dd):(dd))(..)/ 0 show_regexp('Mississippi', /(w+)1/) M<<ississ>>ippi "Time is #$1" "Time is 12:50" "Hour is #$2, minute #$3" "Hour is 12, minute 50" show_regexp('He said "Hello"', /(["']).*?1/) He said <<"Hello">> "AM/PM is #$4" "AM/PM is am" show_regexp("He said 'Hello'", /(["']).*?1/) He said <<'Hello'>> Substitute patterns Upcase every first char a = "the quick brown fox" def mixed_case(name) a.sub(/[aeiou]/, '*') "th* quick brown fox" name.gsub(/bw/) {|word| word.upcase } a.gsub(/[aeiou]/, '*') "th* q**ck br*wn f*x" end a.sub(/sS+/, '') "the brown fox" a.gsub(/sS+/, '') "the" mixed_case("fats waller") "Fats Waller" mixed_case("louis armstrong") "Louis Armstrong" a.sub(/^./) {|match| match.upcase } "The quick brown fox" mixed_case("strength in numbers") "Strength In Numbers" a.gsub(/[aeiou]/) {|vowel| vowel.upcase } "thE qUIck brOwn fOx" 3
  • 4. Classes behind regexps optional args for methods re = /(d+):(d+)/ # match a time hh:mm def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach") re.class -> Regexp "#{arg1}, #{arg2}, #{arg3}." md = re.match("Time: 12:34am") end md.class MatchData md[0] "12:34" # $& cool_dude "Miles, Coltrane, Roach." md[1] "12" # $1 cool_dude("Bart") "Bart, Coltrane, Roach." md[2] "34" # $2 cool_dude("Bart", "Elwood") "Bart, Elwood, Roach." md.pre_match "Time: ” # $` cool_dude("Bart", "Elwood", "Linus") "Bart, Elwood, Linus." md.post_match "am" # $’ Variable number of args code blocks again def varargs(arg1, *rest) def take_block(p1) "Got #{arg1} and #{rest.join(', ')}" if block_given? end yield(p1) else varargs("one") "Got one and " p1 varargs("one", "two") "Got one and two" end varargs "one", "two", "three" "Got one and two, three" end take_block("no block") "no block" take_block("no block") {|s| s.sub(/no /, ‘’) } "block" Capture block explicitly Calling a method class TaxCalculator connection.download_MP3("jitterbug") {|p| show_progress(p) } def initialize(name, &block) @name, @block = name, block File.size("testfile") 66 end Math.sin(Math::PI/4) 0.707106781186548 def get_tax(amount) "#@name on #{amount} = #{ @block.call(amount) }" self.class Object end self.frozen? false end frozen? false tc = TaxCalculator.new("Sales tax") {|amt| amt * 0.075 } self.object_id 969948 tc.get_tax(100) "Sales tax on 100 = 7.5" object_id 969948 tc.get_tax(250) "Sales tax on 250 = 18.75" 4
  • 5. Multiple return values Expanding arrays into args def some_method def five(a, b, c, d, e) 100.times do |num| "I was passed #{a} #{b} #{c} #{d} #{e}" square = num*num end return num, square if square > 1000 end five(1, 2, 3, 4, 5 ) "I was passed 1 2 3 4 5" end five(1, 2, 3, *['a', 'b']) "I was passed 1 2 3 a b" five(*(10..14).to_a) "I was passed 10 11 12 13 14" some_method [32, 1024] num, square = some_method num 32 square 1024 & for procedure objects Keyword args: use Hash print "(t)imes or (p)lus: " class SongList times = gets def create_search(name, params) print "number: " # ... number = Integer(gets) if times =~ /^t/ end calc = lambda {|n| n*number } end else calc = lambda {|n| n+number } list.create_search("short jazz songs", { 'genre' => "jazz", end 'duration_less_than' => 270 }) puts((1..10).collect(&calc).join(", ")) (t)imes or (p)lus: t list.create_search('short jazz songs', 'genre' => 'jazz', number: 2 'duration_less_than' => 270) 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 Expression fun More expressions a=b=c=0 0 rating = case votes_cast [ 3, 1, 7, 0 ].sort.reverse [7, 3, 1, 0] when 0...10 then Rating::SkipThisOne song_type = if song.mp3_type == MP3::Jazz when 10...50 then Rating::CouldDoBetter if song.written < Date.new(1935, 1, 1) else Rating::Rave Song::TradJazz end else Song::Jazz end command expressions: else `date` "Mon Jan 16 22:32:17 CST 2006n" Song::Other end 5