<< Previous Page
    

    
      Table of Contents
    

    
      Next Page >>
    
  
10
%q{Case Statements}

# Use case to match constants
case age
when 5
start_questioning
when 21
start_drinking
end

# Can also match regexes
case order_id
when /^\d+/
handle_online_order(order_id)
when /^offline_(\d+)/
# Use a regex capture
handle_offline_order($1)
else
raise InvalidOrderNumber
end

# Can also match ranges
case age
when 0..12
"child"
when 13..19
"teenager"
when 20..200
"adult"
else
raise InvalidAge
end

# Can also match types
case Math::PI
when String
raise ShouldNotRun
when Float
# executes this code path
when Hash
raise ShouldNotRun
end

# Can also match procs and lambdas
case number
when proc {|x| x.positive?}
"Positive"
when lambda {|x| x.negative?}
"Negative"
end

# Can also match multiple things
case thing
when "one", "two"
# Same types of matchers
when 2..3, 5, 7, Float
# Different types of matchers
end
%q{Regular Expressions}

# You can match a regular expression
/0x[a-f0-9]+/.match '0xabc'
=> #<MatchData "0xabc">

/0x[a-f0-9]+/.match 'abc'
=> nil

# You can also use the match operator
/0x[a-f0-9]+/ =~ '0xabc'
=> 0

/0x[a-f0-9]+/ =~ 'abc'
=> nil

# Scan to count the number of matches
'0xdead 0xbeef'.scan /0x[a-f0-9]+/
=> ["0xdead", "0xbeef"]

'abc'.scan /0x[a-f0-9]+/
=> []

# How to use capture groups
/0x[a-f0-9]+/ =~ '0xabc'
=> 0
$1 => nil

/(0x[a-f0-9]+)/ =~ '0xabc'
=> 0
$1 => "0xabc"

# You can capture more than one
/(def)(ghi)/ =~ 'abcdefghi'
=> 3
$1 => "def"
$2 => "ghi"
$3 => nil

# You can capture backreferences
/(def)(\1)/ =~ 'defdef'
=> 0
$1 => "def"
$2 => "def"
$3 => nil

# $1 is basically the same as:
Regexp.last_match[1]
=> "def"

# Substitute one with regex
'abc,abc,abc'.sub(/abc/, "def")
=> "def,abc,abc"

# Substitute all with regex
'abc,abc,abc'.gsub(/abc/, "def")
=> "def,def,def"
10
    
      << Previous Page
    

    
      Table of Contents
    

    
      Next Page >>