From: Eric Mahurin Date: 2005-08-03T22:14:02+09:00 Subject: Re: [RCR] array or with non-array --- "David A. Black" wrote: > Hi -- > > On Wed, 3 Aug 2005, Eric Mahurin wrote: > > > I think a primary example where I would really like real > > duck-typing in a built-in would be Regexp#match(str). This > > requires the arg to be a String. I would really like to > have > > this be able to operate on a file. If I implement a class > that > > walks like, talks like, quacks like a String but really > > accesses a file (practically did that in my rubyforge > cursor > > project), it wouldn't do any good because Regexp#match only > > takes a String - period. > > You can define #to_str on your object to get Regexp#match to > accept > it as an argument: > > irb(main):006:0> o = Object.new > => # > irb(main):007:0> def o.to_str; "hi"; end > => nil > irb(main):008:0> /i/.match(o) > => # This doesn't really help in the polymorphism department. This is no different than writing: /i/.match(o.to_str) > > The Regexp#match method could be implemented to take ANY > object > > that implemented a some subset of the String API. > > I think there's a semantic or perhaps definitional issue > here, though. > What does it mean for a regular expression to "match" an > arbitrary > object? I don't think it's just a matter of what methods the > object > has. The object has to match the pattern, and the patterns > are > descriptions of strings. I'm not sure how you would detect a > pattern > like /[A-Z]{3}(\d\d)?/ in something that wasn't a string. By the same methods used in String. It could get away with just one method to accomplish the task: #[positive_int]. We could put this in IO for example: class IO def [](i) self.pos = i if eof? # pos can go beyond the eof self.pos = i-1 return(nil) if eof? self.pos = i end getc end end If Regexp#match(obj) used just obj[pos], we could match a Regexp across a file with the above. Like I said earlier, for efficiency the code should special case the String case and use the same implementation there is now. ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs