By Popular Demand, I Give You… Mixer!

“Popular demand,” yeah… right… That’s the ticket. Anyway, I saw this blog entry by Jamie this morning which caused me to write a Ruby program to mix up the letters of words, leaving the first and last letter as they were. I started out with a simple script, then I added better punctuation support, then I converted it to a class, then I wrote unit tests to run it. Anyway, somebody wanted to see it, so here it is. Is it great code? Probably not. Do I care? Not really.

  1  class Mixer  2      private  3      def randomize(str)  4          if str.length < 4  5              return str  6          end  7  8          letters = str.split(//)  9 10          first = letters[0] 11          mid = letters[1..(letters.length - 2)] 12          last = letters[letters.length - 1] 13 14          new_letters = "" 15 16          while mid && mid.length > 0 17              len = mid.length 18              r = rand(len) 19              new_letters << mid.delete_at(r) 20          end 21 22          first + new_letters + last 23      end 24 25      public 26      def mix_file(filename) 27          lines = IO.readlines(filename) 28 29          mix_lines(lines) 30      end 31 32      def mix_string(str) 33          new_str = "" 34 35          mix_lines(str.split).each do |line| 36              new_str << line 37          end 38 39          new_str 40      end 41 42      def mix_lines(lines) 43          lines.collect! do |line| 44              new_line = "" 45 46              line.split(/s+|,|.|!|(|)|"|'/).each do |word| 47                  new_line << randomize(word) << " " 48              end 49 50              new_line 51          end 52 53          lines 54      end 55  end 

And the unit tests, which don’t actually test anything.

  1  require 'test/unit'  2  require 'mix'  3  4  class MixTest < Test::Unit::TestCase  5      def setup()  6          @mixer = Mixer.new  7      end  8  9      def test_word() 10          x = @mixer.mix_string("testing") 11          puts x 12          assert_not_equal("testing", x, "String not randomized") 13      end 14 15      def test_string() 16          x = @mixer.mix_string("this is a humongous test, dangit") 17          puts x 18      end 19 20      def test_file() 21          article = @mixer.mix_file("testfile.txt") 22          #puts article 23      end 24  end 

I’m sure someone will find this useful… Again, “yeah, right.” Ah well, it was a mildly amusing diversion…

Advertisements