Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Dynamic Exception Rescue in Ruby
#!/usr/bin/env ruby
def match_message(regexp)
m = Module.new
(class << m; self; end).instance_eval do
define_method(:===) do |error|
regexp === error.message
end
end
m
end
begin
raise StandardError, "Error message about a socket."
rescue match_message(/socket/) => error
puts "Error #{error.class.name} matches /socket/; ignored."
end
#!/usr/bin/env ruby
def match_message(regexp)
lambda{ |error| regexp === error.message }
end
begin
raise StandardError, "Error message about a socket."
rescue match_message(/socket/) => error
puts "Error #{error.class.name} matches /socket/; ignored."
end
#!/usr/bin/env ruby
require 'benchmark'
def match_message192(regexp)
lambda{ |error| regexp === error.message }
end
def match_message187(regexp)
m = Module.new
(class << m; self; end).instance_eval do
define_method(:===) do |error|
regexp === error.message
end
end
m
end
Benchmark.bm do |x|
x.report { 100_000.times{ match_message192(/socket/); } }
x.report { 100_000.times{ match_message187(/socket/); } }
end

Just came across this. I tried the lambda approach and and getting TypeError in Ruby 2.1.1. It appears that this support has been removed :<

rmg commented Sep 12, 2014

For anyone reaching this page from Google, the 1.8.7 version (straight out of Exceptional Ruby, buy it!) works fine in 2.1.2 :-)

It only appears to work on 1.9.x, something seems to have changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment