Issue #8948 has been updated by Eregon (Benoit Daloze).


We already have immutable (created only once) regexps: it is always the case for literal regexps and for dynamic regexps you need the 'o' flag: /a#{2}b/o.

So there are in practice immutable, but currently not #frozen?. Do you want to request it? I think it makes sense.

You can check with #object_id to know if 2 references reference the same object.

> def r; /ab/; end
> r.object_id
=> 2160323760
> r.object_id
=> 2160323760

> def s; /a#{2}b/; end
> s.object_id
=> 2153197860
> s.object_id
=> 2160163740

> def t; /a#{2}b/o; end
> t.object_id
=> 2160181200
> t.object_id
=> 2160181200
----------------------------------------
Feature #8948: Frozen regex
https://bugs.ruby-lang.org/issues/8948#change-41958

Author: sawa (Tsuyoshi Sawada)
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


=begin
I see that frozen string was accepted for Ruby 2.1, and frozen array and hash are proposed in https://bugs.ruby-lang.org/issues/8909. I feel there is even more use case for a frozen regex, i.e., a regex literal that generates a regex only once. It is frequent to have a regex within a frequently repeated portion of code, and generating the same regex each time is a waste of resource. At the moment, we can have a code like:

    class Foo
      RE1 = /pattern1/
      RE2 = /pattern1/
      RE3 = /pattern1/
      def classify
        case self
        when RE1 then 1
        when RE2 then 2
        when RE3 then 3
        else 4
        end
      end
    end

but suppose we have a frozen `Regexp` literal `//f`. Then we can write like:

    class Foo
      def classify
        case self
        when /pattern1/f then 1
        when /pattern1/f then 2
        when /pattern1/f then 3
        else 4
        end
      end
    end

=end


-- 
http://bugs.ruby-lang.org/