21.3. More Features

21.3.1. Exception Handling


def doSomething(x)
  if x < 10
    raise "value to low"
  end
end

begin
  doSomething(5)
rescue
  print "error: #{$!}\n"
ensure
  print "make sure this is done\n"
end


# user-defined exception

class ChainedException < Exception
  attr :no
  attr :cause
  def initialize(no, cause=nil)
    @no = no
    @cause = cause
  end

  def to_s()
    return "no=#{@no}"
  end
end

def raiseException()
  raise ChainedException.new(123)
end

begin
  raiseException()
rescue ChainedException
  print "error: #{$!}\n"
end

21.3.2. Modules and Mixins

Mixin defining the "to_s" method based on reflection.

module Display
  def to_s()
    s = ""
    for name in instance_variables
      s += "#{name[1..-1]}=#{instance_eval(name)}\n"
    end
    return s
  end
end

# Tiny address class using the Display mixin
class Address include Display
  attr_reader :street, :city, :country
  
  def initialize(street, city, country="Germany")
    @street, @city, @country = street, city, country
  end
end

address = Address.new("Am Seestern 4", "Duesseldorf", "Germany")
print address, "\n"

21.3.3. Operator Overloading

21.3.4. Regular Expressions

Here is a regular expression looking for the "src" parts in HTML image tags.

# regular expression looking for the "src" parts in HTML image tags
# The 'true' argument makes the pattern case insensitive
r = Regexp.compile('(?:input|img).*src=(\'|")(.*)\1', true)

s = "<input type='image' src='images/some.gif'>"
m = r.match(s)
assertEquals("images/some.gif", m[2])

# same in perl style
s =~ /(?:input|img).*src=(\'|")(.*)\1/
assertEquals("images/some.gif", m[2])

The true argument of the compile method makes the pattern case insensitive.