Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Exit from Kernel#match immediately when a pattern is matched

  • Loading branch information...
commit 81639941c08135e2a5f7efb7aa07f581dd62a57c 1 parent aaf10dd
@k-tsj authored
Showing with 8 additions and 9 deletions.
  1. +8 −9 lib/pattern-match.rb
View
17 lib/pattern-match.rb
@@ -374,13 +374,9 @@ def validate
end
class Env < BasicObject
- attr_reader :ret
-
def initialize(ctx, val)
@ctx = ctx
@val = val
- @matched = false
- @ret = nil
end
private
@@ -389,9 +385,11 @@ def with(pat_or_val, guard_proc = nil, &block)
pat = pat_or_val.is_a?(Pattern) ? pat_or_val : PatternValue.new(pat_or_val)
pat.validate
pat.pattern_match_env = self
- if (! @matched) and pat.match(@val) and (guard_proc ? with_tmpbinding(@ctx, pat.binding, &guard_proc) : true)
- @matched = true
- @ret = with_tmpbinding(@ctx, pat.binding, &block)
+ if pat.match(@val) and (guard_proc ? with_tmpbinding(@ctx, pat.binding, &guard_proc) : true)
+ ret = with_tmpbinding(@ctx, pat.binding, &block)
+ ::Kernel.throw(:exit_match, ret)
+ else
+ nil
end
rescue PatternNotMatch
end
@@ -498,8 +496,9 @@ def call_refined_method(obj, name, *args)
obj.__send__(name, *args)
end
end
- env.instance_eval(&block)
- env.ret
+ catch(:exit_match) do
+ env.instance_eval(&block)
+ end
end
case vals.length
when 0
Please sign in to comment.
Something went wrong with that request. Please try again.