Project

General

Profile

Feature #9846

Regexp#to_regexp

Added by wconrad (Wayne Conrad) over 5 years ago. Updated over 2 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:62615]

Description

There should be Regexp#to_regexp, just as there is Array#to_ary and String#to_str.

p [].to_ary       # => []
p ''.to_str       # => ""
p //.to_regexp    # undefined method `to_regexp`...

The use case is code like this:

if o.respond_to?(:to_ary)
  # do something with o.to_ary
elsif o.respond_to?(:to_str)
  # do something with o.to_str
elsif o.respond_to?(to_regexp)    # can't do this today
  # do something with o.to_regexp

The workaround is to use Regexp.try_convert. Regexp.try_convert accepts either a Regexp or an object that responds to #to_regexp; so this code works fine (and is in some ways better):

elsif re = Regexp.try_convert(o)
  # do something with o

Still, that Regexp does not respond to #to_regexp surprised me. Does it surprise anyone else?


Files

History

Updated by justcolin (Colin Fulton) almost 3 years ago

I know this is an old issues, but this also surprised me.

Updated by nobu (Nobuyoshi Nakada) almost 3 years ago

  • Description updated (diff)
case
when ary = Array.try_convert(o)
  # do something with ary
when str = String.try_convert(o)
  # do something with str
when re = Regexp.try_convert(o)
  # do something with re
else
  # do other thing
end

Updated by matz (Yukihiro Matsumoto) over 2 years ago

  • Status changed from Open to Rejected

Is there any concrete use-case? Consistency is not the best reason.
This proposal leads against Duck typing.

Matz.

Also available in: Atom PDF