From: Mike Stok Date: 2006-03-12T01:51:43+09:00 Subject: Re: Help me understand why the Ruby block is slower than wit On 11-Mar-06, at 11:09 AM, Alan Burch wrote: > James Gray wrote: >> On Mar 10, 2006, at 5:28 PM, William James wrote: >> >>> File.open("wordlist") { |f| >>> while w = f.gets >>> puts w if w.size==11 && w.split(//).uniq.size == 11 >>> end >>> } >> >> That's what the foreach() iterator is for: >> >> File.foreach("wordlist") do |word| >> puts word if word.chomp.split("").uniq.size == 10 >> end >> >> James Edward Gray II > > James: > This code doesn't work on my Mac. I do have a version that uses the > file block and each/foreach above, but I'm suspecting that when the > string becomes an array after the split something's breaking down as I > get words of all sizes out??? > Doesn't James Gray's code print out words which contain exactly 11 different letters e.g. abbreviations - 13 characters + \n, but because it wasn't checked for size before splitting this boils down to 10 different characters. irb(main):001:0> s = 'abbreviations' => "abbreviations" irb(main):002:0> s.split('').uniq => ["a", "b", "r", "e", "v", "i", "t", "o", "n", "s"] irb(main):003:0> s.split('').uniq.size => 10 Interesting. I crudely benchmarked this (using time on my mac): #!/usr/bin/env ruby File.foreach("K6wordlist.txt") do |word| # puts word if word.size==11 && word.split(//).uniq.size == 11 puts word if word.length == 11 and word.chomp.split (//).uniq.size == 10 # puts word if word.length == 11 and not word =~ /(.).*\1/ end and then ran each of the three sending output to /dev/null (after checking that they all worked the same on my test file. In order: real 0m0.347s user 0m0.294s sys 0m0.017s real 0m0.334s user 0m0.288s sys 0m0.018s real 0m0.177s user 0m0.137s sys 0m0.015s There may be interesting behaviour if the last line in the file doesn't have a trailing \n, I would probably go for something more like File.foreach("K6wordlist.txt") do |word| word.chomp! puts word if word.length == 10 and not word =~ /(.).*\1/ end (timing intentionally omitted :-) Mike -- Mike Stok http://www.stok.ca/~mike/ The "`Stok' disclaimers" apply.