Project

General

Profile

Feature #9846

Updated by nobu (Nobuyoshi Nakada) almost 8 years ago

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

 ```ruby 
 String#to_str. 

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

  

 The use case is code like this: 

 ```ruby 
 

     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 
     elseif 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.    `Regexp.try_convert` Regexp.try_convert accepts either a `Regexp` Regexp or an object that responds to `#to_regexp`; #to_regexp; so this code works fine (and is in some ways better): 

 ```ruby 
 

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

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

Back