ruby picture

RCR 258: supply hash to Regexp.new

Submitted by neoneye (Wed Jun 02 19:06:48 UTC 2004)

Abstract

Regexp.new is C'ish and old. Reworking the arguments may help maintainability of it.

Problem

Magic values are in general bad.

  Regexp::IGNORECASE = 1
    Regexp::EXTENDED = 2
   Regexp::MULTILINE = 4</pre></p>

The lang option are abbreviated with:
   unicode = 'U' 

    
   none = 'N'
   euc = 'E'</pre></p>

You can easy make ugly things
Regexp.new('pattern', 7, 'U')

  

Proposal

Use option hash instead.

Regexp.new('pattern', :ignorecase=>true, :extended=>true, :multiline=>true, :encoding=>:UTF8)

I have some more ideas for useful options: :interpret_warnings_as_errors, :verbose_mismatch, :suppress_warnings.

Analysis

compatibility can be maintained, by using ducktyping on the options argument.

If its type are Integer, then use old-style. If type are hash then its new-style.

Implementation

class Regexp2
  def initialize(pattern, options={})
    p options
  end
end
Regexp2.new('abc', :encoding=>:big5, :suppress_warnings=>true)
ruby picture
Comments Current voting

Additional note: IMHO the encoding name should follow some standard naming scheme (encoding names, use String or Symbol) used all over Ruby. (Is there such a thing already?) We might even want some package method that can emit all known encoding names.

Robert Klemme


> compatibility can be maintained, by using ducktyping on the options argument. > If its type are Integer, then use old-style. If type are hash then its new-style.

I think you mean 'by *not* using ducktyping' :-) Anyway, however it's implemented, I'm voting in favor. I don't use this stuff much but I agree about the crypticness of the existing syntax.

-- David Black


I would only suggest that the format be changed to be more like what will be expected of Ruby2's named arguments, rather than a hash. -- Austin Ziegler


Without looking at the code, can't we just "yield self if block_given?". -- Daniel Berger


Strongly opposed 0
Opposed 0
Neutral 2
In favor 14
Strongly advocate 1
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .