From: "Brian Schröder" Date: 2005-08-08T21:43:32+09:00 Subject: Re: String#to_ary and Test::Unit On 08/08/05, Trans wrote: > > David A. Black wrote: > > This message is in MIME format. The first part should be readable text, > > while the remaining parts are likely unreadable without MIME-aware tools. > > > > Hi -- > > > > On Mon, 8 Aug 2005, [ISO-8859-1] Brian Schr�der wrote: > > > > > Another sidenote that removes the need for to_ary completely and is a > > > lot faster: > > > > It's not needed if it's OK just to call #each, but I thought the > > #to_ary call was part of Tom's original requirement. > > Unfortunately David is correct. In looking more closely at your > (Brian's) code offering, I see that it still uses #each. So in the > context of String, the same problem arsies --I can't count on a string > being iterated over by chars. I'll have to create an overriding #freq > method specifically for string --and the other methods that work the > same way. > > T. > > Yes, but why not use: probability_hash = "this is my string".split(//).freq Each object that could support to_ary can also support each, while not every object that has an each makes sense with to_ary. So it would seem better to me to put this functionality into the enumerable and supply an enumerable. Then you can even do module CharString def each(&block) self.split(//).each &block end end module WordString def each(&block) self.split(/\s+/).each &block end end charstring = "some chars" class << charstring include CharString end charstring.freq_brian => {" "=>0.1, "a"=>0.1, "m"=>0.1, "c"=>0.1, "o"=>0.1, "e"=>0.1, "r"=>0.1, "h"=>0.1, "s"=>0.2} wordstring = "This is my word string" class << wordstring include WordString end wordstring.freq_brian => {"my"=>0.2, "word"=>0.2, "This"=>0.2, "string"=>0.2, "is"=>0.2} hth, brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/