From: Bill Kelly Date: 2001-12-12T21:16:34+09:00 Subject: [ruby-talk:28339] Re: Reviews solicited for Ruby article From: "Stephan K�mper" > > Hi Harry, > > great to see people working on articles to spread thw word! > > Harry Ohlsen wrote: > > Are there any errors in the code ... or can it be written more > > clearly/succinctly, without making it hard for someone who hasn't seen > > the language before to understand? > > > > Any suggestions on how to better explain anything? > > > > Feel free to post comments to the newsgroup ... I'm not easily offended > > :-) ... but if you could send me an e-mail, that would be helpful, > > because then I can send you a quick message when I have newer versions. > > > > Thanks in advance, > > > > Harry O. > > Well, I'm not through the whloe thing but I've got a comment on the > first example. Well counting the "Hello world" one it's actually the > 2nd one. You'll know what I mean anyway. > > IMHO the count_uppercase could me made more rubyish like the following: > > def count_uppercase( text ) > # "Initialize" the hash with 0 and you can use it right away > # w/o the need to init each used element with 0 > counts = Hash.new(0) > # Used an iterator here - it's more native in Ruby I think > text.each_byte { | c | > # Had to convert c to chr as each_byte leaves me with a Fixnum > c = c.chr > counts[c] += 1 if c =~ /[A-Z]/ > } Alternately, counts = Hash.new(0) text.scan(/[A-Z]/).each {|c| counts[c] += 1} would possibly be fun to include in addition to the text.each_byte approach . . . . sort of a footnote to convey some of Ruby's versatility? > total = 0 > # I'd prefer curly braces here, > # but how am I to tell what to use when? > counts.each_pair do |key, value| > puts "#{key} -> #{value}" > total += value > end > total > end > > total = count_uppercase("This is only an EXAMPLE !!") > > puts "The total was #{total}" > > > From an oo point of view I'd prefer to change some more things > - One and only one job for each method > Make a distinction between output and computing > count_uppercase shoud do what its name implies: Count the uppercase > letters > Perhaps it should return the hash with the counting results? > > - The output in count_uppercase might be refactored out of this method I'd agree with these suggestions too. > Anyway, I'll be happy to see suggestions to improve what I posted. > > Happy rubying! > > Stephan Regards, Bill