Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Regexp#fixed_encoding?

rxp.fixed_encoding? → true or false

Returns false if rxp is applicable to a string with any ASCII compatible encoding. Returns true otherwise.

Example
r = /a/
r.fixed_encoding?                               #=> false
r =~ "\u{6666} a"                               #=> 2
r =~ "\xa1\xa2 a".force_encoding("euc-jp")      #=> 2
r =~ "abc".force_encoding("euc-jp")             #=> 0

r = /a/u
r.fixed_encoding?                               #=> true
r.encoding                                      #=> #<Encoding:UTF-8>
r =~ "\u{6666} a"                               #=> 2
r =~ "\xa1\xa2".force_encoding("euc-jp")        #=> Encoding::CompatibilityError
r =~ "abc".force_encoding("euc-jp")             #=> 0

r = /\u{6666}/
r.fixed_encoding?                               #=> true
r.encoding                                      #=> #<Encoding:UTF-8>
r =~ "\u{6666} a"                               #=> 0
r =~ "\xa1\xa2".force_encoding("euc-jp")        #=> Encoding::CompatibilityError
r =~ "abc".force_encoding("euc-jp")             #=> nil
See also #eql? #hash #encoding #inspect also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0