<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Moose56 blog &#187; Ruby</title>
	<atom:link href="http://www.moose56.com/blog/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.moose56.com/blog</link>
	<description></description>
	<lastBuildDate>Fri, 13 Jan 2012 07:24:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>TitleCase</title>
		<link>http://www.moose56.com/blog/2008/05/22/titlecase/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=titlecase</link>
		<comments>http://www.moose56.com/blog/2008/05/22/titlecase/#comments</comments>
		<pubDate>Thu, 22 May 2008 03:40:36 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/?p=53</guid>
		<description><![CDATA[John Gruber posted his title case script the other day which prompted a request from Dan Benjamin to convert it into Ruby. This is my quick and dirty attempt. If only I was such a highly skilled regexp ninja as Gruber is!. #!/usr/bin/env ruby -wKU class TitleCase @small_words = %w(a an and as at but [...]]]></description>
			<content:encoded><![CDATA[<p>John Gruber posted his <a href="http://daringfireball.net/2008/05/title_case">title case</a> script the other day which prompted a request from <a href="http://hivelogic.com">Dan Benjamin</a> to convert it into Ruby. This is my quick and dirty attempt. </p>
<p>If only I was such a highly skilled regexp ninja as Gruber is!.</p>
<p><span id="more-41"></span></p>
<p>
<pre class="viewsource"><code class="ruby">
#!/usr/bin/env ruby -wKU

class TitleCase

  @small_words    = %w(a an and as at but by en for if in of on or the to v[.]? via vs[.]?);
  @small_words_r  = /(#{@small_words.join("|")})b/
  @inline_period  = /[[:alpha:]|[:digit:]][.][[:alpha:]|[:digit:]]/
  @special_case   = /AT&#038;T|Q&#038;A/i
  @uppercase_word = /[[:upper:]]{2,}/

  # Static/Class method to do the work
  def TitleCase.parse(str)

    result = []

    # split on white space
    str.each("s") do |word|

      word.strip!

      # do not downcase SEC etc.
      if @uppercase_word.match(word) then result << word; next end

      word.downcase!
      # capitalise all but small_words_r and inline_period
      word.capitalize! unless @small_words_r.match(word) || @inline_period.match(word)
      # deal with special cases
      word.upcase! if @special_case.match(word)

      result << word
    end

    # capitalize first and last word
    result[0].capitalize! unless @inline_period.match(result[0])
    result[result.size-1].capitalize! unless @inline_period.match(result[result.size-1])

    result.join(" ")
  end

end

# Test line
#puts TitleCase.parse("Does this work? a an this is daringfireball.net vs. hivelogic.com")

text = STDIN.gets
puts TitleCase.parse(text)
</code></pre></p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/05/22/titlecase/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSSpress</title>
		<link>http://www.moose56.com/blog/2008/05/16/csspress/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=csspress</link>
		<comments>http://www.moose56.com/blog/2008/05/16/csspress/#comments</comments>
		<pubDate>Fri, 16 May 2008 20:51:35 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/?p=52</guid>
		<description><![CDATA[So today I launched a little command line application for compressing CSS files. My main motivations for this were that I wanted a little tool to strip out comments and whitespace as well as crunch down some of the style values into more optimized versions. As well as this I wanted to write a program [...]]]></description>
			<content:encoded><![CDATA[<p>So today I launched a little command line application for compressing CSS files.</p>
<p><span id="more-40"></span></p>
<p>My main motivations for this were that I wanted a little tool to strip out comments and whitespace as well as crunch down some of the style values into more optimized versions. As well as this I wanted to write a program in Ruby that someone else might actually find usefull as well as help me learn a little more about the language.</p>
<p>Currently it can do a pretty good job of removing the comments and the white space and I am working on the rest. You can find out more about it at <a href="http://www.csspress.net">csspress.net</a>.</p>
<h3>A long road</h3>
<p>What follows is a little account of how I got this far with it. If you don&#8217;t care about implementation stuff you probably don&#8217;t want to read on.</p>
<p>In order to distribute the tool I found that by packaging my application as a <a href="http://www.rubygems.org/">RubyGem</a> and hosting it on <a href="http://rubyforge.org/">RubyForge</a> anyone can download it simply by typing sudo gem install csspress (anyone on a mac that is) and they can use it right away. No difficult messing with source code.</p>
<p>In terms of writing it in Ruby, that was not crucial to the programs operation. From the users point of view they don&#8217;t care what its implemented in, only that it works. The advantage of using Ruby from my point of view is that I like programming with it and with the gem system it makes it child&#8217;s play to deploy it.</p>
<h3>Gems</h3>
<p>In order to package your code as a gem you have to use a specific directory structure. I already had a rudimentary working version of my application so I had to fit it in around this structure. It was a little trial and error at first and then I found <a href="http://newgem.rubyforge.org/">New Gem Generator</a>, this provides a command that generates the directory structure and as well as a load of useful files and rake tasks. You might find it a bit over the top (is so try <a href="http://seattlerb.rubyforge.org/hoe/">Hoe</a>), but after spending a bit of time and a little more trial and error I have come to really like it.</p>
<h3>Tips</h3>
<p>If you use a version control system like Subversion or Git you should ignore the doc/ and pkg/ directories as well as the index.html file, as these contain files that will change a lot and cause you a lot of problems.</p>
<p>I also found it useful to have a dig about in some of the gems I already had installed on my system. Its really good to see how other people have done it before you.<br />
<h3>What&#8217;s coming</h3>
<p>If I am honest it took me longer to set up the gem, SVN repository and rubyforge account than it did to write the program. Now its all in place though I can now get cracking on improving the tool and adding functionality.</p>
<p>Download it and give it a go; you might find it useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/05/16/csspress/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binary Tree in Ruby</title>
		<link>http://www.moose56.com/blog/2008/05/09/binary-tree-in-ruby/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=binary-tree-in-ruby</link>
		<comments>http://www.moose56.com/blog/2008/05/09/binary-tree-in-ruby/#comments</comments>
		<pubDate>Fri, 09 May 2008 15:55:25 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/05/09/binary-tree-in-ruby/</guid>
		<description><![CDATA[Today I thought I would have a play at implementing a binary tree in ruby and see if I could dig up any things I had not used before. I first came up with a RSpec for it and set about building it and reading about the different methods you can use. Here is the [...]]]></description>
			<content:encoded><![CDATA[<p>Today I thought I would have a play at implementing a binary tree in ruby and see if I could dig up any things I had not used before.
<p>
<span id="more-39"></span></p>
<p>I first came up with a <a href="http://rspec.info/">RSpec</a> for it and set about building it and reading about the different methods you can use.</p>
<p>Here is the spec I came up with (This is the complete one, at the beginning they were all pending):</p>
<p>
<pre class="viewsource"><code class="ruby">
require "binary_tree"

describe BinaryTree do

  before(:each) do
    @tree = BinaryTree.new
    @keys = %w{F B G A D I C E H}
    @keys.each {|key| @tree.insert(key)}
  end

  it "should have a node for each key inserted" do
    @keys.each do |key|
     @tree.has?(key).should == true
    end
  end

  it "should have the same number of keys as there are nodes" do
    num = 0
    @tree.traverse_inorder do |node|
      num += 1
    end
    num.should eql(@keys.size)
  end

  it "should be tarversable in-order" do
    expected = %w{A B C D E F G H I}
    actual = []
    @tree.traverse_inorder do |node|
      actual << node.key
    end
    expected.should == actual
  end

  it "should be tarversable pre-order" do
    expected = %w{F B A D C E G I H}
    actual = []
    @tree.traverse_preorder do |node|
      actual << node.key
    end
    expected.should == actual
  end

  it "should be tarversable post-order" do
    expected = %w{A C E D B H I G F}
    actual = []
    @tree.traverse_postorder do |node|
      actual << node.key
    end
    expected.should == actual
  end

  it "should be able to return a node when given a key which it contains" do
    @tree.insert("Z")
    "Z".should == @tree.search("Z").key
  end

  it "should return nil if no matching key is found" do
    nil.should == @tree.search("Z")
  end

  it "should be able to delete nodes"

  it "should remain balanced following insertion and deletion of nodes"

end
</code></pre>
</p>
<p>As you can see there are still two to implement. The code that meets this specification is below.</p>
<p>
<pre class="viewsource"><code class="ruby">
# This class stores the tree and handles the insertion
# of new keys. Once the initial key has been inserted
# the insertion is handled by the node objects in the tree.
#
# Traversal of the tree is also controled by this class and
# can be pre-order, post-order or in-order by calling the
# relavant method.
#
# The BinaryTree should be able to store any object that includes
# the Comparable module.
#
# ====TODO
# - Impliment tree balancing
# - Impliment node deletion
#
class BinaryTree

  # This class represents a single node in the tree.
  # It holds a key and references to both its left
  # and right sub trees.
  #
  # It is also able to determin if it is a leaf node
  # using the .leaf? method.
  #
  class Node
    attr_reader :key, :left, :right

    # Create a Node and store the key as well
    # as its left and right sub trees.
    #
    def initialize( key, left=nil, right=nil )
      @key = key
      @left, @right = left, right
    end

    # Insert a new key into the correct subtree based on the
    # value of &lt;i&gt;self&lt;/i&gt;.
    #
    # Duplicate keys are ignored.
    #
    def insert( key )
      if key &lt; @key
        # insert left
        @left.nil?  ? @left  = Node.new( key ) : @left.insert( key )
      elsif key &gt; @key
        # insert right
        @right.nil? ? @right = Node.new( key ) : @right.insert( key )
      end # duplicate key, do nothing
    end

    # Test if &lt;i&gt;self&lt;/i&gt; is a leaf node.
    #
    def leaf?
      @left.nil? &#038;&#038; @right.nil?
    end

    # Return the Key of &lt;i&gt;self&lt;/i&gt; as a String
    #
    def to_s
      @key.to_s
    end
  end

  attr_reader :root

  # Create a new BinaryTree
  #
  def initialize
    @root = nil
  end

  # call-seq:
  #   insert(key) -> self
  #
  # Add a new key to &lt;i&gt;self&lt;/i&gt;
  #
  # Eamples:
  #   tree = BinaryTree.new
  #   tree.insert(5).insert(2).insert(8).insert(1)
  #
  def insert( key )
    if @root.nil?
      @root = Node.new( key )
    else
      @root.insert( key )
    end
    self
  end

  # call-seq:
  #   traverse_inorder {|node| block } -> self
  #
  # Traverses &lt;i&gt;self&lt;/i&gt; in-order.
  #
  # Calls &lt;i&gt;block&lt;/i&gt; once for each node in &lt;i&gt;self&lt;/i&gt;, passing that
  # Node as a parameter.
  #
  # Eamples:
  #   tree = BinaryTree.new
  #   tree.insert(5).insert(2).insert(8).insert(1)
  #
  #   tree.traverse_inorder { |node| print "#{node} " } # -> 1 2 5 8
  #
  def traverse_inorder( node=@root, &#038;block )
    return if node.nil?
    traverse_inorder( node.left,  &#038;block )
    yield node
    traverse_inorder( node.right, &#038;block )
  end

  # call-seq:
  #   traverse_preorder {|node| block } -> self
  #
  # Traverses &lt;i&gt;self&lt;/i&gt; pre-order.
  #
  # Calls &lt;i&gt;block&lt;/i&gt; once for each node in &lt;i&gt;self&lt;/i&gt;, passing that
  # Node as a parameter.
  #
  # Eamples:
  #   tree = BinaryTree.new
  #   tree.insert(5).insert(2).insert(8).insert(1)
  #
  #   tree.traverse_preorder { |node| print "#{node} " } # -> 5 2 1 8
  #
  def traverse_preorder( node=@root, &#038;block )
    return if node.nil?
    yield node
    traverse_preorder( node.left,  &#038;block )
    traverse_preorder( node.right, &#038;block )
  end

  # call-seq:
  #   traverse_postorder {|node| block } -> self
  #
  # Traverses &lt;i&gt;self&lt;/i&gt; post-order.
  #
  # Calls &lt;i&gt;block&lt;/i&gt; once for each node in &lt;i&gt;self&lt;/i&gt;, passing that
  # Node as a parameter.
  #
  # Eamples:
  #   tree = BinaryTree.new
  #   tree.insert(5).insert(2).insert(8).insert(1)
  #
  #   tree.traverse_postorder { |node| print "#{node} " } # -> 1 2 8 5
  #
  def traverse_postorder( node=@root, &#038;block )
    return if node.nil?
    traverse_postorder( node.left,  &#038;block )
    traverse_postorder( node.right, &#038;block )
    yield node
  end

  # call-seq:
  #   search(key) -> aNode
  #
  # Search &lt;i&gt;self&lt;/i&gt; for &lt;i&gt;key&lt;/i&gt; returning the Node if found
  # or nil if not.
  #
  def search( key, node=@root )
    return nil if node.nil?
    if key &lt; node.key
      search(key, node.left)
    elsif key &gt; node.key:
      search(key, node.right)
    else
      return node
    end
  end

  # Test &lt;i&gt;self&lt;/i&gt; for &lt;i&gt;key&lt;/i&gt;.
  #
  def has?( key )
    not self.search(key).nil?
  end
end
</code></pre>
</p>
<p>Download all the code from here: <a href='http://moose56.com/blog/wp-content/uploads/2008/05/binary_tree.tgz' title='binary_tree.tgz'>binary_tree.tgz</a> and have a play. All the comments have been written with RDoc in mind so the documentation that is generated is quite nice. This example may give someone a helpful working example of RSpec and RDoc.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/05/09/binary-tree-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Needleman-Wunsch algorithm in Ruby</title>
		<link>http://www.moose56.com/blog/2008/04/17/needleman-wunsch-algorithm-in-ruby/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=needleman-wunsch-algorithm-in-ruby</link>
		<comments>http://www.moose56.com/blog/2008/04/17/needleman-wunsch-algorithm-in-ruby/#comments</comments>
		<pubDate>Thu, 17 Apr 2008 11:58:41 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/04/17/needleman-wunsch-algorithm-in-ruby/</guid>
		<description><![CDATA[While at university I had the pleasure of studying bioinformatics. Bioinformatics is all about using the processing power of computers to lean about and infer data from DNA and protein sequences. For example if you want to find the common parts of a DNA sequence from 500 different sequences and each sequence is 50000 bases [...]]]></description>
			<content:encoded><![CDATA[<p>While at university I had the pleasure of studying bioinformatics. Bioinformatics is all about using the processing power of computers to lean about and infer data from DNA and protein sequences.</p>
<p>For example if you want to find the common parts of a DNA sequence from 500 different sequences and each sequence is 50000 bases long it will take some time to compare them all and you are bound to make some mistakes.</p>
<p>This is where bioinformatics comes in and uses tried and tested computer science principles to make these large tasks easier, more accurate and faster. One example is the Needleman-Wunsch algorithm which is used to score a string of bases against another.</p>
<p><span id="more-38"></span></p>
<p>The course I was on covered this and it also came up in the exam. Although no code implementation of the algorithm was provided I found making a working copy very helpful in understanding it as well as getting some coding practice.</p>
<p>My inital version was in Java but I re-wrote it in Ruby as some of the abilities of the language regarding overriding of array methods made it slightly more terse.
<p>I list my code below to help people in the future as well as a number of resources that helped me</p>
<h3>Resources</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Needleman-Wunsch_algorithm">The Wikipedia description of the algorithm</a></li>
<li><a href="http://snippets.dzone.com/posts/show/2199">A Ruby implementation of the Wikipedia sudo code</a></li>
<li><a href="http://ruby.brian-schroeder.de/editierdistanz/">Ruby and Python version of the Edit distance algorithm by Brian Schroeder</a> (the algorithm is similar to N-W)</li>
</ul>
<h3>Code</h3>
<p>
<pre class="viewsource"><code class="ruby">
# The cell object holds the value of an allignment
# and the location of the previous cell
class Cell
  @@valid_paths = [:ABOVE, :LEFT, <img src='http://www.moose56.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> IAG, nil]
  attr_reader :value, :path_from

  def initialize(value, path_from=nil)
    raise "Invalid path: '#{path_from}'" unless @@valid_paths.include?(path_from)
    @value = value
    @path_from = path_from
  end

  # This enables comparison between one cell to another.
  def <=>(other)
    self.value <=> other.value
  end
end</code></pre>
</p>
<p>
<pre class="viewsource"><code class="ruby">
# The grid object is a generic 2D array which can store any object.
# In this case it stores Cell objects and provides a numbers of
# functions to make traversing and accessing the grid cleaner
class Grid
  # 2D array initalised to nil
  def initialize(number_of_rows, number_of_cols)
    @grid = Array.new(number_of_rows){Array.new(number_of_cols){nil}}
  end

  # Allows use of [x,y] over [x][y]
  def [](row, column)
    @grid[row][column]
  end

  # Allows use of [x,y]=z over [x][y]=z
  def []=(row, column, value)
    @grid[row][column] = value
  end

  # Loops through each index to negate the need for
  # nested loops or blocks in other parts of the code
  def each_index
    @grid.each_with_index do |row, row_index|
      row.each_with_index do |col, column_index|
        yield row_index, column_index
      end
    end
  end

  # Returns each row array from the grid.
  # Not convinced how usefull this is
  def each
    @grid.each do |row|
      yield row
    end
  end

  # Very basic output of the grid
  def to_s
    @grid.map{ |row| row.join("t") }.join("n")
  end
end</code></pre>
</p>
<p>
<pre class="viewsource"><code class="ruby">
class NeedlemanMunch

  attr_reader :score, :allignment

  def initialize(reference_seq, comparison_seq, similarity_matrix, gap_penalty=-1)

    @ref_sq, @comp_sq = reference_seq , comparison_seq

    # Size of f_matrix
    @cols = @ref_sq.size+1
    @rows = @comp_sq.size+1

    # Allignment score params
    @gap_pen = gap_penalty
    @sim_matrix = similarity_matrix

    # Matrix creation
    @f_matrix = Grid.new(@rows, @cols)

    # Results
    @score = nil
    @allignment = nil

    # Calcultate the allignment and score
    # then trace the path
    calculate_f_matrix
    trace_path
  end

  def print_f_matrix
    output = ""
    @f_matrix.each do |row|
      line = ""
      row.each do |col|
        line << "#{col.value}:#{col.path_from}t"
      end
      output << line << "n"
    end
    output
  end

  def to_s
    puts @allignment
  end

private

  def calculate_f_matrix
    @f_matrix.each_index do |r, c|
      @f_matrix[r,c] =
        if    first_cel?(r,c) then Cell.new(0)
        elsif first_col?(r,c) then Cell.new(@f_matrix[r-1,c].value + @gap_pen)
        elsif first_row?(r,c) then Cell.new(@f_matrix[r,c-1].value + @gap_pen)
        else  calc_cell(r,c)
      end
    end
    @score = @f_matrix[@rows-1,@cols-1].value
  end

  # Three functions that determin the location
  # of a cell in the grid based on the coords
  def first_cel?(row, col) row==0 &#038;&#038; col==0 end
  def first_row?(row, col) row==0 &#038;&#038; col!=0 end
  def first_col?(row, col) row!=0 &#038;&#038; col==0 end

  # Calculate the value of the cell based on the 3 surrounding
  # cells, the dynamic programming bit.
  def calc_cell(row, col)
    [Cell.new(@f_matrix[row-1, col  ].value + @gap_pen, :ABOVE),
     Cell.new(@f_matrix[row,   col-1].value + @gap_pen, :LEFT),
     Cell.new(@f_matrix[row-1, col-1].value + match_score(row,col), <img src='http://www.moose56.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> IAG)].max
  end

  # Get the score for 2 bases from the similarity matrix
  def match_score(row, col)
    @sim_matrix[(@ref_sq[col-1].chr + @comp_sq[row-1].chr).upcase]
  end

  # Function: trace_path
  #
  # When the f_matrix for both sequences has been
  # calculated the allignment must be worked out.
  #
  def trace_path
    ref = ''
    seq = ''
    i = @comp_sq.length
    j = @ref_sq.length

    # This is currently a horrid case statement
    # that crawls back through the f_matrix looking
    # at each cells path_from attribute to determin
    # the allignment of the two sequences.
    #
    # This will determin one allignment, there may be
    # others!
    while (i>0 and j>0)
      current = @f_matrix[i,j]

      case current.path_from
      when <img src='http://www.moose56.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> IAG
        ref = @comp_sq[i-1].chr << ref
        seq = @ref_sq[j-1].chr << seq
        i -= 1
        j -= 1
      when :ABOVE
        ref = @comp_sq[i-1].chr + ref
        seq = '-' << seq
        i -= 1
      when :LEFT
        ref = '-' << ref
        seq = @ref_sq[j-1].chr + seq
        j-= 1
      else
        # Something has gone wrong
        raise UnknownPathError
      end
    end

    while (i>0)
      ref = @comp_sq[i-1].chr + ref
      seq = '-' << seq
      i-=1
    end

    while (j > 0)
      ref = '-' + ref
      seq = @ref_sq[j-1].chr << seq
      j -= 1
    end
    @allignment = [seq , ref]
  end
end</code></pre>
</p>
<p>
<pre class="viewsource"><code class="ruby">
class UnknownPathError &lt; StandardError; end</code></pre>
</p>
<p>
<pre class="viewsource"><code class="ruby">
if __FILE__ == $0

  example = 2

  # a few similarity matrix options for you to try
  if example == 1

    similarity_matrix = {
      'AA' => 10, 'AG' => -1, 'AC' => -3, 'AT' => -4,
      'GA' => -1, 'GG' =>  7, 'GC' => -5, 'GT' => -3,
      'CA' => -3, 'CG' => -5, 'CC' =>  9, 'CT' =>  0,
      'TA' => -4, 'TG' => -3, 'TC' =>  0, 'TT' =>  8
    }
    gap_penalty = -5
    a = 'GAATTCAGTTA'
    b = 'GGATCGA'

  elsif example == 2

    similarity_matrix = {
      'AA' =>  2, 'AG' => -1, 'AC' => -1, 'AT' => -1,
      'GA' => -1, 'GG' =>  2, 'GC' => -1, 'GT' => -1,
      'CA' => -1, 'CG' => -1, 'CC' =>  2, 'CT' => -1,
      'TA' => -1, 'TG' => -1, 'TC' => -1, 'TT' =>  2
    }
    gap_penalty = -1
    a = 'ACCGGTAT'
    b = 'ACCTATC'

  elsif example == 3

    similarity_matrix = {
      'AA' => 1, 'AG' => 0, 'AC' => 0, 'AT' => 0,
      'GA' => 0, 'GG' => 1, 'GC' => 0, 'GT' => 0,
      'CA' => 0, 'CG' => 0, 'CC' => 1, 'CT' => 0,
      'TA' => 0, 'TG' => 0, 'TC' => 0, 'TT' => 1
    }
    gap_penalty = 0
    a = 'AGACTAGTTAC'
    b = 'CGAGACGT'

  end

  nm = NeedlemanMunch.new(a, b, similarity_matrix, gap_penalty)
  puts nm.allignment
  puts nm.score
  puts nm.print_f_matrix
end</code></pre>
</p>
<p>Hope this helps someone even if it is just with some Ruby stuff.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/04/17/needleman-wunsch-algorithm-in-ruby/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Palindrome: Java &amp; Ruby</title>
		<link>http://www.moose56.com/blog/2008/01/24/palindrome-java-ruby/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=palindrome-java-ruby</link>
		<comments>http://www.moose56.com/blog/2008/01/24/palindrome-java-ruby/#comments</comments>
		<pubDate>Thu, 24 Jan 2008 15:00:00 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/01/24/palindrome-java-ruby/</guid>
		<description><![CDATA[One thing that programming students often have to implement is a program to tell whether or not a string is a palindrome. In this post I flex my dusty Java and demonstrate a simple palindrome detector. Java First off just in case you are not sure, a palindrome is a string that reads the same [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that programming students often have to implement is a program to tell whether or not a string is a palindrome. In this post I flex my dusty Java and demonstrate a simple palindrome detector.</p>
<p><span id="more-135"></span></p>
<h2>Java</h2>
<p>First off just in case you are not sure, a palindrome is a string that reads the same forwards as it does backwards. e.g madam</p>
<p>So to solve this I guess we need a method called pallindrome()</p>
<pre class="viewsource"><code class="java">
public static boolean isPalindrome (String word) {
    if (word.equalsIgnoreCase(reverse(word))) { return true; }
    else { return false; }
}
</code></pre>
<p>So here we have a method called isPalindrome that takes a string and returns true or false depending on the success of the if statement. The line that performs the test is:</p>
<pre class="viewsource"><code class="java">
word.equalsIgnoreCase(reverse(word))
</code></pre>
<p>This uses the Java String method equalsIgnoreCase to test if word is equal to the result of reverse(word). If true then it is a palindrome.</p>
<p>So what is missing from this code? the implementation of the reverse method. There are many ways to reverse a String, below is my first attempt</p>
<pre class="viewsource"><code class="java">
public static String reverse (String in) {
    String out = "";
    for (int i=0; i&lt;in.length(); i++) {
        out += String.valueOf(in.charAt((in.length()-1)-i));
    }
    return out;
}
</code></pre>
<p>This is a typical loop through the characters in a string in reverse and build up another string with these characters and then return this new string. All fine and good, then I googled a bit and found out that the Java StringBuffer object has a native reverse method so I can rewrite the method as follows:</p>
<pre class="viewsource"><code class="java">
public static String reverse (String in) {
    StringBuffer sb = new StringBuffer(in).reverse();
    return sb.toString();
}
</code></pre>
<p>As well as being fewer lines of code this is far more clear than a the for loop method.</p>
<h3>Things to take note of</h3>
<p>The reason I split the palindrome method and reverse method instead of having them as one was to improve the testability of the code. It also increases the chances of reuse as it is forceable that I may want the reverse method at a later date on it own without the palindrome stuff.</p>
<p>This is not a perfect implementation. The second to you stick more than one word into isPalindrome it will fall down because at the moment it will not ignore space characters so a palindrome such as &#8216;nurses run&#8217; will return false</p>
<p>It may not be totally perfect but I enjoyed the exorcise and feel it must be better than the version I came up with 6 years ago on my introduction to programming course.</p>
<h2>Ruby</h2>
<p>Yes yes, I know another Ruby version of perfectly good code, but the main reason I include it is that its really cool (well for me anyway). This is because the Ruby String object has a reverse method already and because of the open nature of Ruby classes you can add a palindrome method to Ruby&#8217;s String without any inheritance stuff. Take a look:</p>
<pre class="viewsource"><code class="ruby">
class String
 def palindrome?
   self == self.reverse
 end
end

"madam".palindrome? # returns true
</code></pre>
<p>I really like this method, but of course with great power comes great responsibility and open classes are not always a good idea.</p>
<h2>Update</h2>
<p>So reading more into this it appears that the Java string buffer method might be faster and more efficient than the loop method. The reason for this is that when Java converts the loop method into byte code it substitutes the string concatenation operator for a string buffer and uses the append method. It does this for every concat operation and uses the default buffer size of 16 characters.</p>
<p>Some other factors to take into consideration are that if a null string, empty string  or a single character are passed in. A null string will cause a NullPointerException so it is important that it is dealt with. If an empty or one character string is entered they should be returned strait away and no string buffer object created because they are already a reverse of them selves. This means a slight change to the method:</p>
<pre class="viewsource"><code class="java">
public static String reverse (String str) {
    if (str == null) {
        // kick out an error
        throw new NullPointerException( "reverse passed null String" );
    } else if (str.length() &lt;= 1) {
        // string is already revesed
       return str;
    }
    // use the StringBuffer to reverse str
    return new StringBuffer(str).reverse().toString();
}
</code></pre>
<p>Here are some good resources on this topic. I really love the way that you can google something and it turns up a load of stuff that can really help in how you approach a problem and give advice on the merits of different solutions. It really helps improve you.</p>
<ul>
<li><a href="http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html">StringBuffer versus String</a></li>
<li><a href="http://www.rgagnon.com/javadetails/java-0129.html">Optimizing string operations</a></li>
<li><a href="http://lists.ibiblio.org/pipermail/dev-dpml/2005q1/000657.html">NullPointerExceptions</a></li>
<li><a href="http://stephan.reposita.org/archives/2007/11/09/java-interview-questions-write-a-string-reverser-and-use-recursion/">A great blog on reversing strings with java</a></li>
</ul>
<p>Lastly I tried a few different Java methods for reversing a String. You can find the results <a href="http://moose56.com/blog/2008/01/25/java-string-reverse-methods-analysed">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/01/24/palindrome-java-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sending an email with PHP and Ruby</title>
		<link>http://www.moose56.com/blog/2008/01/23/sending-an-email-with-php-and-ruby/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sending-an-email-with-php-and-ruby</link>
		<comments>http://www.moose56.com/blog/2008/01/23/sending-an-email-with-php-and-ruby/#comments</comments>
		<pubDate>Wed, 23 Jan 2008 12:26:48 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/01/23/sending-an-email-with-php-and-ruby/</guid>
		<description><![CDATA[The other day I was trying to code a back end to a simple web form. I wanted the data entered into the form to be emailed back to me. Here I describe two very simple methods to send an email from both PHP and Ruby code. So why am I posting this? Well it [...]]]></description>
			<content:encoded><![CDATA[<p>The other day I was trying to code a back end to a simple web form. I wanted the data entered into the form to be emailed back to me. Here I describe two very simple methods to send an email from both PHP and Ruby code.</p>
<p><span id="more-13"></span></p>
<p>So why am I posting this? Well it took a bit of fishing to find some of the information so I thought this might help someone in the future. Also if you google anything to do with Ruby and web development you can&#8217;t get away from heaps Rails stuff which is not what I was after so this post might help.</p>
<h2>PHP</h2>
<p>PHP was built for this sort of thing so I was expecting it to be pretty easy and I was not disappointed. The actual function to send a mail is called&#8230;yep mail. The php documentation lists it as:</p>
<pre class="viewsource"><code class="php">bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )</code></pre>
<p>With this its simple to code up a working version:</p>
<pre class="viewsource"><code class="php">
// pick up values from form
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];

// create email message
$from = $email;
$to = "some@address.com";
$subject = "Some subject";
$message = wordwrap(stripcslashes($comment), 70);
$headers = "From: $name &lt;$from&gt;" . "rn";

// send email
mail($to, $subject, $message, $headers);
</code></pre>
<p>Thats it, simply point the action attribute of your form to this script file and it will pick up the form data and send it off in an email to who ever you want.</p>
<p>Obviously this is a pretty basic example and you would need to add some form validation and a redirect when the script has completed otherwise the user will be directed to a totally blank page.</p>
<p>One other cool thing is that because the mail funciton returns a bool to can stick it in an if statement:</p>
<pre class="viewsource"><code class="php">
if (!mail($to, $subject, $message, $headers)){
  // redirect to fatal error page
  // or stick an entry in a log file
  // exit the script
}

//everything fine and dandy, continue
</code></pre>
<h2>Ruby</h2>
<p>Ok so I tried it in Ruby because it is my current language du jour and I did not want to see it outdone by PHP. Sadly however I have to admit it was not as simple as the PHP method.  Here is the listing:</p>
<pre class="viewsource"><code class="ruby">
require "net/smtp"

# set up smtp object
server = Net::SMTP.new('you.domain.com', 25,
  'localhost.localdomain', 'username', 'password', :login)

# message template
myMessage = &lt;&lt;END_OF_MESSAGE
From: Name &lt;some.address@mail.com&gt;
To: Name &lt;some@address.com&gt;
Subject: Some subject

This is the message text
END_OF_MESSAGE

# send the email
server.start do |smtp|
  smtp.sendmail myMessage, "from@mail.com",
    "to@mail.com", "to@mail.com"
end
</code></pre>
<p>There are a few more things to set up in the Ruby version, namely an SMTP object. This is because to send the email you need to provide a SMTP server. You do this by providing the domain, port number and if needed the username and password plus the authentication type of your domains SMTP server.</p>
<p>The sendmail method then takes the message, from address, and a list of addresses to send the email to.</p>
<p>One thing to note is that both sendmail and start can kick out a load of different errors so it would be better to wrap it in a begin rescue statement.</p>
<p>A few resources for the ruby version are:</p>
<ul>
<li><a href="http://ruby.about.com/od/tutorials/ss/ruby_email.htm">A fuller tutorial than this</a></li>
<li><a href="http://www.ruby-doc.org/stdlib/libdoc/net/smtp/rdoc/index.html">Ruby doc for NET::SMTP</a></li>
<li><a href="http://spariamsgems.blogspot.com/2007/12/sending-e-mail-with-ruby-netsmtp.html">Another good example of the Ruby method</a></li>
</ul>
<p>Ok I admit this was a very brief intro into sending email from code using Ruby or PHP, but I hope It might point some people in the right direction.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/01/23/sending-an-email-with-php-and-ruby/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Web site development with StaticMatic</title>
		<link>http://www.moose56.com/blog/2008/01/11/web-site-development-with-staticmatic/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=web-site-development-with-staticmatic</link>
		<comments>http://www.moose56.com/blog/2008/01/11/web-site-development-with-staticmatic/#comments</comments>
		<pubDate>Fri, 11 Jan 2008 12:39:41 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/01/11/web-site-development-with-staticmatic/</guid>
		<description><![CDATA[StaticMatic is a small framework for producing static web sites. It is built on top of a number of Ruby gems such as Haml and makes it possible to create totally static sites using Ruby. I have spent a bit of time playing with StaticMatic and thought I would share some of the things I [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://staticmatic.rubyforge.org/">StaticMatic</a> is a small framework for producing static web sites. It is built on top of a number of Ruby gems such as <a href="http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html">Haml</a> and makes it possible to create totally static sites using Ruby.</p>
<p>I have spent a bit of time playing with StaticMatic and thought I would share some of the things I have learnt just in case anyone else has the same questions as I did.</p>
<p><span id="more-12"></span></p>
<h2>Haml Syntax Highlighting</h2>
<p>First off I use TextMate for editing. In order to make more sense of the the Haml markup which I was totally new to, I found this page with a link to a svn repository where you can download a TextMate bundle for Haml: <a href="http://wincent.com/knowledge-base/Installing_the_Haml_TextMate_bundle">Installing the Haml TextMate bundle</a>. The only difference I had with the instructions was that I had to create a bundles directory which is no big deal. After that I switched TextMate&#8217;s language association option (located at the bottom of the window) to Ruby Haml and everything was great. I also found that the Blackboard theme worked quite will with it.</p>
<h2>Setting up Helpers</h2>
<p>As StaicMatic is based in part on Ruby on Rails there is the ability to define helper functions. There is even a page on the StaticMatic website where developers can upload there own for others to use.</p>
<p>The problem I had was that I could not find out how to set up a helper function in words of one syllable in the documentation and had to piece it together from a few different sources.</p>
<p>When you create your StaticMatic site it will make an empty directory called helpers, but thats it. In order to add a helper function to your site you need to create a file in this directory called application_helper.rb (think rails). In this add the module definition:</p>
<pre><code class="ruby">
module ApplicationHelper
end
</code></pre>
<p>Add any function you like to this module and it will be available to you from all haml files simply buy using:</p>
<pre class="viewsource"><code class="ruby">
= function_name(params)
</code></pre>
<h2>Using Partials</h2>
<p>This is pretty strait forward but may catch some out (it did me). If you place a partial directly in the partials directory do not prefix the filename with an underscore or it will not be able to find the partial file.</p>
<h2>Things to look out for</h2>
<p>I had a lot of problems with tab characters in my Haml files. This is very annoying as the page will not display and the error message from the terminal is not useful at all. The best way I found to overcome it was to use soft tabs, 2 characters wide and if I pasted in any code to always manually re-indent it. This is a pain I know, but so is bug hunting an invisible bug for hours.</p>
<p>Hope this is of some help to some one, below is a list of the web pages I have found useful.</p>
<ul>
<li><a href="http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html">Haml docs</a></li>
<li><a href="http://wincent.com/knowledge-base/Installing_the_Haml_TextMate_bundle">Install TextMate bundle</a></li>
<li><a href="http://www.planetrubyonrails.org/show/feed/187">Some tips from Planet Ruby on Rails</a></li>
<li><a href="http://www.danielfischer.com/2007/11/08/static-websites-the-ruby-way-part-2/">Tips from Daniel Fischer</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/01/11/web-site-development-with-staticmatic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

