From: Bob Gustafson Date: 2001-08-07T06:02:23+09:00 Subject: [ruby-talk:19251] Re: My 1st look @ ruby: No prototypes and problem with String#gsub >Hello -- > >On Sat, 4 Aug 2001, Stefan Scholl wrote: > >> class Shuffle >> def initialize(data) >> raise(TypeError, "not an array") if data.type != Array >> @store = data >> @mark = Array.new >> @marked = 0 >> end >> >> def each >> while @marked < @store.length >> while @mark[i = rand(@store.length)] >> end >> @mark[i] = true >> @marked += 1 >> yield @store[i].gsub(/ /, '\\ ') >> end >> end >> end >> >> Shuffle.new(ARGV).each {|s| print "#{s} " } > > >This seems like a lot of code to write, and variables to use, to get >this to happen. Also, I don't think Shuffle makes for a very good >class. Shuffling is a more method-like concept. It's also a general >enough thing that you could make a case for adding it directly to >class Array. It might be handy to have a "bang" (modify in place) >version and a non-bang version: > > class Array > def my_shuffle! > size.times do > push slice! rand(size) > end > self > end > > def my_shuffle > dup.my_shuffle! > end > end > > ARGV.my_shuffle.each do |e| > print e.gsub(/ /, '\\\\\&') + " " > end > > >(Maybe some mathematician could check this for correctness :-) It >actually runs pretty fast for non-huge arrays, if I'm remembering some >old benchmark results correctly.) > > >David > >-- >David Alan Black You might take the urge to check 'types' of arguments as a subliminal signal to think over the code again. As David Black has suggested, coding shuffle as a method seems more elegant and 'object oriented'. There is no need to check 'types' with this arrangement because the method is part of the toolset for that class and it only sees objects of that class. BobG