<?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>Jacob Repp &#187; ruby</title>
	<atom:link href="http://jrepp.com/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://jrepp.com</link>
	<description>Game programming, music and life</description>
	<lastBuildDate>Fri, 03 Sep 2010 04:39:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Tracking down Circular Dependencies in Static Libraries</title>
		<link>http://jrepp.com/2009/06/26/tracking-down-circular-dependencies-in-static-libraries/</link>
		<comments>http://jrepp.com/2009/06/26/tracking-down-circular-dependencies-in-static-libraries/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 23:18:51 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[linking]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://jrepp.com/2009/06/26/tracking-down-circular-dependencies-in-static-libraries/</guid>
		<description><![CDATA[The GNU linker has some trouble when you present it with multiple library archives that depend upon each other. Libraries with symbols resolved in other libraries must be presented earlier on the command line. You can work around this with &#8230; <a href="http://jrepp.com/2009/06/26/tracking-down-circular-dependencies-in-static-libraries/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The GNU linker has some trouble when you present it with multiple library archives that depend upon each other. Libraries with symbols resolved in other libraries must be presented earlier on the command line. You can work around this with a command line argument:</p>

<pre><code>"--start-group", "--end-group", aternatively "-(" "-)"
</code></pre>

<p><a href="http://linux.die.net/man/1/ld">See the man page for LD for more info</a></p>

<p>Unfortunately this argument comes with the following little warning:</p>

<blockquote>
  <p>Using this option has a significant performance cost. It is best to use it only when there are unavoidable circular references between two or more archives. </p>
</blockquote>

<p>The particular case I was dealing with was the havok version 6 libraries on linux. I was advised that there may be way to link them but hadn&#8217;t been worked out. In order to test this theory I hacked together a little bit of ruby to show library dependencies. I feel this may be of some use to someone else so I present it here:</p>

<pre><code>require 'find'

$symbs = {}
$archives = []

class Archive
    attr_reader :name, :symbs, :depends, :undef
    def initialize name
        @name = name
        @symbs = {}
        @undef = {}
        @depends = Hash.new(0)
    end

    def add_definition loc, name
        @symbs[name] = loc
        $symbs[name] = self
    end

    def add_undefined name
    @undef[name] = 0
    end

    def resolve_undefined
        @undef.each do |k,v|
            archive = $symbs[k]
           if not archive or archive == self then
                next
            end
            @undef[k] = archive
            @depends[archive] = @depends[archive] + 1
        end
    end
end

Find.find('.') do |path|
    next if not /.a$/.match(path)

    io = IO.popen("nm #{path}")
    archive = Archive.new(path)
    $archives &lt;&lt; archive
    while (str = io.gets) do
        case str
        when /\w+\.a/
            archive = Archive.new(str)
            puts "archive: #{str}"
        when /[A-F0-9]+ [A-Za-z] \w+/
            parts = str.split
            archive.add_definition parts[0], parts[2]
        when /\s+U\s+\w+/
            archive.add_undefined str.split[1]
        end
   end
   puts "processed #{path}, #{archive.symbs.count} defined, #{archive.undef.count} undefined"
end

$archives.each do |archive|
    archive.resolve_undefined
end

$archives.sort! {|a,b| a.depends.count &lt;=&gt; b.depends.count }

puts "dependency list:"
$archives.each do |archive|
    puts "#{archive.name}: #{archive.depends.count}"
    archive.depends.each do |depend,count|
        puts "    #{depend.name}: #{count}"
    end
end
</code></pre>

<p>The final solution was to simply remove the object files from the static libraries and put them into a single combined library:</p>

<pre><code>rm *.o
find . -name \*.a -exec ar x {} \;
ar rcs libHavok.a *.o
ranlib libHavok.a
rm *.o
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2009/06/26/tracking-down-circular-dependencies-in-static-libraries/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Austin Ruby Meetup 1-17-2008</title>
		<link>http://jrepp.com/2008/01/17/austin-ruby-meetup-1-17-2008/</link>
		<comments>http://jrepp.com/2008/01/17/austin-ruby-meetup-1-17-2008/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 06:14:52 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[meetup]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://jrepp.com/2008/01/17/austin-ruby-meetup-1-17-2008/</guid>
		<description><![CDATA[We had a good time at the meetup tonight. Steven and I busted out the laptops and shared some code and ideas. He had a nice rails app for learning Latin that supported a tagging architecture. I know next to &#8230; <a href="http://jrepp.com/2008/01/17/austin-ruby-meetup-1-17-2008/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We had a good time at <a href="http://ruby.meetup.com/97/">the meetup tonight</a>. Steven and I busted out the laptops and shared some code and ideas. He had a nice rails app for learning Latin that supported a tagging architecture. I know next to nothing about rails so it was interesting to see the interactive console and scaffolding at work. We talked a bit about lisp compilation, writing, philosophy and open source vs. closed source. I demonstrated how you can specialize a method in SBCL using <strong>THE</strong> type declarations and the difference it makes in the generated machine code via <strong>DISASSEMBLE</strong>. As usual it was entertaining and enriching. If you&#8217;re in the Austin area and want to talk Ruby, Lisp, Python, C or whatever you should consider joining us.</p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2008/01/17/austin-ruby-meetup-1-17-2008/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Build Huffman Compression in Ruby</title>
		<link>http://jrepp.com/2008/01/08/build-huffman-compression-in-ruby/</link>
		<comments>http://jrepp.com/2008/01/08/build-huffman-compression-in-ruby/#comments</comments>
		<pubDate>Tue, 08 Jan 2008 03:19:21 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://jrepp.com/2008/01/08/build-huffman-compression-in-ruby/</guid>
		<description><![CDATA[Many wonderful things can be done with binary trees. One brilliant usage of the binary tree was proposed by David Huffman in 1951 at MIT which has since become the foundation for much of the compression technology available today. Huffman &#8230; <a href="http://jrepp.com/2008/01/08/build-huffman-compression-in-ruby/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Many wonderful things can be done with binary trees. One brilliant usage of the binary tree was proposed by <a href="http://en.wikipedia.org/wiki/Huffman_coding">David Huffman in 1951 at MIT</a> which has since become the foundation for much of the compression technology available today. Huffman discovered a simple way to generate a provable minimal binary encoding given a set of input symbols. It&#8217;s a deep subject, and one which I&#8217;d eventually like to spend more time getting into. For now I&#8217;ll walk through how this simple idea can be used to implement some decent compression using pure Ruby.</p>

<p>First of all you have your basic binary tree representation. I previously showed a <a href="http://jrepp.com/2008/01/07/build-a-binary-tree-in-ruby/">simple binary tree example</a> that demonstrates how binary trees are easily manipulated in ruby. Every binary tree node holds a value and links off to a right and left nodes that may also hold values. A leaf node is a node with dead links (left and right are both set to nil). </p>

<p>In the Huffman tree the leaves contain a single symbol while interior nodes summarize their sub-tree. I have simplified the idea so that all nodes wrap what is called an association list (assoc list). This is an old lisp idiom of a list containing name value pairs in the form ((name value) (name value)). To find a value in an association list you just walk the list looking at the first element of each sub-list. A reverse association list (rassoc list) takes the same form as an assoc list with the name and value pair swapped. For very small sets of data the performance of assoc lists is better than deeper structures such as a hash or tree. Ruby provides a few array APIs to deal with assoc and rassoc lists. I always store a rassoc list with the (occurance count, symbol) in a leaf and a sum of all contained lists in interior nodes. None of this information is important in understanding how Huffman encoding works but I use this concept below so I thought I should at least call it out.</p>

<pre><code>class Node
    # binary tree representation
    attr_accessor :value, :left, :right
    def initialize(value=nil, left=nil, right=nil)
        @value, @left, @right = value, left, right
    end
    def leaf?
        return @left == nil &amp;&amp; @right == nil
    end
end
</code></pre>

<p>By default the node is initialized to be empty with no links. A simple query method &#8216;leaf?&#8217; is added for some syntactic sugar below when dealing with the tree.</p>

<p>The first step in building the Huffman tree is to build a set of occurrences for the data you want to encode. Some algorithms are able to this dynamically for streams of data but in this case I walk the entire input text first to find all symbols. In this implementation a symbol is a single character. Keep in mind that it is possible to use words or other unique symbols instead of single characters which could result in better compression. </p>

<pre><code>def occurrences(text)
    # return an ordered array of [occurrences, character] ascending order
    occ = Hash.new(0)
    text.scan /./m do |b| occ[b] += 1 end 
    return occ.keys.map {|k| [occ[k], k]}.sort
end
</code></pre>

<p>The hash table <strong>occ</strong> is initialized with a default value of zero which causes all new entries to start at zero. Every character of the text is scanned and the characters are counted using the hash table. The final stage is to create an array of [count, character] entries in sorted order. Map executes the block over each key looking up the value of the key and outputting a single rassoc element per hash entry.</p>

<p>The final stage in building the tree is to convert the list into a tree representation. The occurrence entries are converted into leaf nodes and put into a queue in ascending order. Two entries are removed from the queue merged onto an interior node and placed onto a second queue. The interior node sums the rassoc list from both nodes that are consumed. If there are no nodes in the primary queue a node will be removed from the secondary queue. The final node remaining is the root of the tree.</p>

<pre><code>def huffman(occlist)
    # build a huffman encoding binary tree from the occurrence list
    if occlist.empty? then
        puts "warning: no occurrences provided to build huffman tree"
        return nil
    end

    # create the initial queue with leaves, trees contain assoc lists
    leaves = occlist.map {|entry| Node.new([entry]) }
    interior = []
    deq = lambda {
        if (leaves.length &gt; 0) then leaves.delete_at 0 
        else interior.delete_at 0 end
    }

    # create interior nodes
    while leaves.length + interior.length &gt; 1
        l, r = deq.call, deq.call
        node = Node.new(l.value + r.value, l, r)
        interior &lt;&lt; node
    end

    deq.call
end
</code></pre>

<p>Interior nodes are only formed in the second portion of the Huffman build function. It will only consume leaf nodes or or other interior nodes that represent the edge of the tree. In this way the tree is built bottom up and balanced.</p>

<p>Next up is a bit of a utility function that takes a Huffman tree and a symbol and converts it into an array of 0s and 1s that represent the binary encoding of the symbol. Walking the tree is represented by a 0 or 1 for the left and right sub-trees respectively.</p>

<pre><code>def bits(ht, sym)
    # given a tree and symbol return an array of encoded bits  
    def bits_internal(ht, sym, enc)
        return enc, nil if not ht
        return enc, ht.value if ht.leaf?

        if ht.left.value.rassoc(sym) != nil
            enc &lt;&lt; 0
            bits_internal(ht.left, sym, enc)
        else
            enc &lt;&lt; 1
            bits_internal(ht.right, sym, enc)
        end
    end

    if ht.value.rassoc(sym) == nil
        puts "warning: no binary encoding for: '#{sym}'"
        return []
    end

    enc, value = bits_internal(ht, sym, [])
    if value[0][1] != sym 
        puts "warning: binary encoding: #{enc.inspect}, value: #{value.inspect} does not match '#{sym}'"
        return []    
    else
        return enc
    end
end
</code></pre>

<p>Bits makes use of the internally stored assoc lists to figure out which sub-tree should be visited. There are more efficient ways to implement this but this method is fine for example purposes. Bits() uses an internal method bits<em>internal() which is implemented in a recursive style similar to visit() from the previous binary tree code. Bits does a bit of error checking on the result from bits</em>internal() before returning the encoding value back to the caller.</p>

<p>Similar to bits_internal() above decode() will visit the tree using the binary representation in an array and choose the left or right sub-trees. Each time decode calls itself it uses a slice of the original array. If you are familiar with lisp code this method of traversal will look very familiar. When we have arrived at a leaf we know that we have found the symbol and it is returned.</p>

<pre><code>def decode(ht, bits)
    if ht.leaf? 
        return ht.value[0][1]
    end

    case bits[0]
        when 0 
            decode(ht.left, bits[1..bits.length-1])
        when 1 
            decode(ht.right, bits[1..bits.length-1])
    end
end
</code></pre>

<p>Now for a simple test of the Huffman encoding procedures above. The standard Lorem Ipsum text will be used. The <a href="http://lipsum.com/">history of this randomized Latin text</a> is very interesting, it is extracted from an early text on ethics by Cicero which was written in 45 BC.</p>

<pre><code>text = &lt;&lt;TEXT
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed est nulla, suscipit vel, tempus sit amet, viverra sit amet, dui. Nunc ultrices, purus vulputate luctus sodales, mauris augue elementum diam, in ornare neque nisi pharetra lectus. In hac habitasse platea dictumst. Phasellus justo turpis, laoreet id, semper at, convallis a, nisi. Duis iaculis erat et mauris. Donec a arcu. Ut sed risus vel mi mollis vehicula. Aenean laoreet, lorem dapibus aliquam ultrices, ante velit vestibulum sem, vel molestie arcu elit sit amet nunc. Vivamus venenatis placerat dui. Mauris porttitor varius velit. 
TEXT
</code></pre>

<p>To measure the effectiveness of the compression I will sum the bits of the raw text assuming each character were to take a modern standard byte (8bits). </p>

<pre><code># build a huffman encoding tree
ht = huffman(occurances(text))

# measure the compression
bitsum = 0
for c in text.scan /./m
    bitsum += bits(ht, c).length
end

orig = text.length
new = bitsum / 8.0
printf("original %s bytes, huffman encoded: %s bytes, ratio: %.2f%%", 
orig, new, new/orig*100)
</code></pre>

<p>And what do we get for our efforts on this humble piece of ruby code:</p>

<pre><code>original 598 bytes, huffman encoded: 374.25 bytes, ratio: 62.58%
</code></pre>

<p>~63% compression ratio. Not too shabby! </p>

<p><a href="http://jrepp.com/code/huffman.rb.txt">Click here to view the sample source code</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2008/01/08/build-huffman-compression-in-ruby/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Build a Binary Tree in Ruby</title>
		<link>http://jrepp.com/2008/01/07/build-a-binary-tree-in-ruby/</link>
		<comments>http://jrepp.com/2008/01/07/build-a-binary-tree-in-ruby/#comments</comments>
		<pubDate>Mon, 07 Jan 2008 06:29:24 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://jrepp.com/2008/01/07/build-a-binary-tree-in-ruby/</guid>
		<description><![CDATA[Building algorithms in ruby is fun and rewarding. This binary tree doesn&#8217;t balance itself but it is simple and flexible using ruby blocks for visit and insert. Traversal style can be selected optionally to visit with :inorder, :preorder or :postorder. &#8230; <a href="http://jrepp.com/2008/01/07/build-a-binary-tree-in-ruby/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Building algorithms in ruby is fun and rewarding. This binary tree doesn&#8217;t balance itself but it is simple and flexible using ruby blocks for visit and insert. Traversal style can be selected optionally to visit with :inorder, :preorder or :postorder.</p>

<p>Here&#8217;s your basic binary tree node representation, it holds a value and connects to a left and right node:</p>

<pre><code>class Node
    # binary tree representation
    attr_accessor :value, :left, :right
    def initialize(value=nil, left=nil, right=nil)
        @value, @left, @right = value, left, right
    end
end
</code></pre>

<p>Insert receives a value and a block which is responsible for doing the comparison. Comparison would normally be done with the Ruby <strong>&lt;=></strong> operator (this is the case later when the chunkybacon is inserted into the tree). The block passed to insert receives two elements and should yield a -1 for less, 1 for greater or 0 for equal. This function is implemented in terms of itself, notable for it&#8217;s lack of any balancing.</p>

<pre><code>def insert(node, v, &amp;block)
    # binary tree insert without balancing, 
    # block performs the comparison operation
    return Node.new(v) if not node
    case block[v, node.value]
        when -1 
            node.left = insert(node.left, v, &amp;block)
        when 1 
            node.right = insert(node.right, v, &amp;block)
    end
    return node
end
</code></pre>

<p>Visit receives the order that the nodes should be visited as well as a block that will act as a visitor of the stored values. This function is also implemented in terms of itself.</p>

<pre><code>def visit(n, order=:preorder, &amp;block)
    # visit nodes in a binary tree, order can be determinied
    # block performs visit action
    return false unless (n != nil)

    case order 
        when :preorder 
            yield n.value
            visit(n.left, order, &amp;block)
            visit(n.right, order, &amp;block)
        when :inorder
            visit(n.left, order, &amp;block)
            yield n.value
            visit(n.right, order, &amp;block)
        when :postorder
            visit(n.left, order, &amp;block)
            visit(n.right, order, &amp;block)
            yield n.value
    end
end
</code></pre>

<p>And here is a simple example of inserting the string &#8216;chunkybacon&#8217; into the binary tree. The result of visiting this tree using :inorder traversal is the string &#8216;abchknouy&#8217;.</p>

<pre><code>if $0 == __FILE__
    # a simple test case
    root = nil
    "chunkybacon".scan(/./m) {|c| root = insert(root, c) {|a,b| a&lt;=&gt;b}}
    visit(root, :inorder) {|v| print v}
end
</code></pre>

<p>You may like it you will see, try it, try it and leave a comment for me.</p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2008/01/07/build-a-binary-tree-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Alternatives to Lexical Binding with Ruby</title>
		<link>http://jrepp.com/2008/01/06/alternatives-to-lexical-binding-with-ruby/</link>
		<comments>http://jrepp.com/2008/01/06/alternatives-to-lexical-binding-with-ruby/#comments</comments>
		<pubDate>Sun, 06 Jan 2008 02:18:46 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://jrepp.com/2008/01/06/alternatives-to-lexical-binding-with-ruby/</guid>
		<description><![CDATA[In ruby the default way to get a name to return a value is via ruby&#8217;s lexical scoping rules. Lexical scoping rules use the way the code is written to determine what a variable name means. You can read the &#8230; <a href="http://jrepp.com/2008/01/06/alternatives-to-lexical-binding-with-ruby/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In ruby the default way to get a name to return a value is via ruby&#8217;s lexical scoping rules. Lexical scoping rules use the way the code is written to determine what a variable name means. You can read the code and understand what a variable will mean when a certain piece of code runs. The alternative to lexical binding is dynamic binding. Dynamic binding determines the value of a variable by the process executing the code. Dynamic binding has a potential to be more confusing because code written this way could have a variety of meanings depending on how the code is executed. Old versions of lisp used dynamic binding by default. In common lisp lexical binding is the default but it is still possible to make a variable dynamically bound. </p>

<p>There are certain scenarios where dynamic binding is particularly useful. It allows the caller to directly control the callee without using any intermediate objects, instead only using the underlying call chain. Certain forms of generic programming become very easy with dynamic binding.</p>

<p>Consider the following as an illustration of implicit dynamic binding:</p>

<pre><code>def print_list(a_list)
  puts a_list.join(separator or ', ')  
end

print_list([1, 2, 3]) # -&gt; 1, 2, 3
separator = ' '
print_list([1, 2, 3]) # -&gt; 1 2 3
</code></pre>

<p>The simple example above also illustrates how <em>implicit</em> dynamic binding in a programming language can really start to dirty up a perfectly good code base. An unfortunate misspelling would be hard to debug in such a language. Additionally various rules about encapsulation are broken along the way.</p>

<p>The dynamic binding style still does have it uses however, especially in a language that supports functional abstraction. In ruby it is possible to define your own function objects and pass them around easily.</p>

<pre><code>my_lambda = lambda {|x| puts x + 10 }
my_lambda.call(1) # -&gt; 11
my_lambda.call(2) # -&gt; 12
</code></pre>

<p>The lambda method in <a href="http://ruby-doc.org/core/classes/Kernel.html#M005970">Kernel#lambda</a> returns a new <a href="http://ruby-doc.org/core/classes/Proc.html">Proc</a> that wraps the code in the block &#8216;{}&#8217;.</p>

<p>In some cases it could be useful to define a dynamically bound lambda that defines actor behavior in a generic way.</p>

<pre><code>def execute_all(actor_list, proc)
  actor_list.each {|actor| actor.execute(proc) }
end
execute_all(lambda {play_anim(anim_family, 'walk', speed) }
</code></pre>

<p>The details of the lambda are open to the interpretation of the actor at the time the code runs. I&#8217;m not of the opinion that this is the best way to write this code but it certainly wins in brevity and in being fairly generic. There are better examples of using dynamic binding in the common lisp system.</p>

<p>To contrast dynamic binding here is an example of lexical binding. The lambda defined here binds <strong>a_var</strong> at the point the lambda is written, not where it is run (hence lexical scoping). This create a lexical <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">closure</a> which <em>closes over</em> the definition of <strong>a_var</strong> to keep it around later. The value returned below is <strong>1</strong> although at the time the code runs there is a binding for <strong>a_var</strong> that changes it&#8217;s meaning to <strong>2</strong>.</p>

<pre><code>def foo(p)
   a_var = 2
   puts p.call
end
a_var = 1
foo(lambda { a_var }) # -&gt; 1
</code></pre>

<p>If ruby used dynamic binding by default the output of the code snipped above would be <strong>2</strong>. To resolve a dynamically bound variable you walk up the chain of current activation records to find the nearest variable binding. In ruby the lexical variable binding captures a lot, including the current &#8216;self&#8217;, block iterator, and locals.</p>

<p>Now that I&#8217;ve covered all that I can talk about ruby tools for working with the bindings and different ways to program with a more dynamic mode.</p>

<p>In ruby it is possible to access the binding from code. The kernel method <a href="http://ruby-doc.org/core/classes/Kernel.html#M005971">binding</a> offers the caller access to an opaque Binding object. Currently the only way to use this binding object that I have found is via eval().</p>

<pre><code>def foo()
  a = 1
  return binding
end

b = foo()
eval('puts a', b) # -&gt; 1
</code></pre>

<p>The binding is manually captured here and passed into eval. This is a form of explicit dynamic binding. The only drawback of this method is that it doesn&#8217;t work for forms that have already been evaluated. </p>

<p>Explicit run-time variable binding is a pretty <a href="http://c2.com/cgi/wiki?ContextParameter">common software pattern</a>. The alternative that is often used in C++ or Java is to create a special context object which is passed as a parameter to a method. The context is a way of explicitly controlling the binding. You create a custom mapping object (a hash for example) and pass it around to create your own variable binding. Here&#8217;s an example:</p>

<pre><code>def foo(ctx, proc)
    puts proc.call() # -&gt; 1
    ctx[:x] = 2
    puts proc.call() # -&gt; 2
end

ctx = {:x=&gt;1}
foo(ctx, lambda {|ctx| ctx[:x] })
</code></pre>

<p>Wouldn&#8217;t it be nice if we could encapsulate this pattern without requiring the extra parameter, dictionary mapping and extra indirection of having to make all variable access through the mapping?</p>

<p>I haven&#8217;t looked at the C code changes that would be required to ruby to do this but I think it&#8217;s possible to roll this pattern of coding directly into the ruby built-in library.</p>

<p>The additions are <code>Binding#from_hash(aHash)</code>, <code>Proc#call_with_binding(aBinding)</code>.</p>

<pre><code>def let(k, &amp;block)
  block.call_with_binding(Binding.from_hash(k))
end

let('a_var'=&gt;1) {
  puts a_var
} # -&gt; 1

dynamic_bound = lambda {
  puts a_var
}
a_var = 1
dynamic_bound.call_with_binding(binding) # -&gt; 1

a_var = 2
dynamic_bound.call_with_binding(binding) # -&gt; 2
</code></pre>

<p>The above code is a hypothetical approach. One that might be interesting to implement. There is one more alternative to lexical binding in ruby that I discovered after I had initially written this post. It relies directly or indirectly on the usage of instance_eval. Here&#8217;s a simple example:</p>

<pre><code>class Foo
  def initialize(a) @a = a end
end

f = Foo.new(1)
f.class.send(:define_method, :foo, lambda { puts @a })
f.foo # -&gt; 1

f2 = Foo.new(2)
f2.foo # -&gt; 2
</code></pre>

<p>The method :define_method defines the proc in terms of Foo. The <strong>@a</strong> binds to the meaning of <strong>@a</strong> in the context of an instance of Foo.</p>

<p>A less permanent way to do this is to use instance_eval directly:</p>

<pre><code>f.instance_eval { @a = @a + 10 }
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2008/01/06/alternatives-to-lexical-binding-with-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using VIM as an Interactive Ruby Environment</title>
		<link>http://jrepp.com/2008/01/05/using-vim-as-an-interactive-ruby-environment/</link>
		<comments>http://jrepp.com/2008/01/05/using-vim-as-an-interactive-ruby-environment/#comments</comments>
		<pubDate>Sat, 05 Jan 2008 22:39:03 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://jrepp.com/2008/01/05/using-vim-as-an-interactive-ruby-environment/</guid>
		<description><![CDATA[I&#8217;m working on some ruby code today on a cleanly installed vim. I decided to improve my editing experience a bit and found some a couple enhancements that work quite nice together. Evaluate ruby with the press of a button &#8230; <a href="http://jrepp.com/2008/01/05/using-vim-as-an-interactive-ruby-environment/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working on some ruby code today on a cleanly installed vim. I decided to improve my editing experience a bit and found some a couple enhancements that work quite nice together.</p>

<h3>Evaluate ruby with the press of a button</h3>

<p>You can see the source of this tip from the <a href="http://vim.wikia.com/wiki/VimTip1244">vim wiki</a>. I find the last bit of code the best of them:</p>

<pre><code>function! Ruby_eval_vsplit() range
  let src = tempname()
  let dst = "Ruby Output"
  " put current buffer's content in a temp file
  silent execute ": " . a:firstline . "," . a:lastline . "w " . src
  " open the preview window
  silent execute ":pedit! " . dst
  " change to preview window
  wincmd P
  " set options
  setlocal buftype=nofile
  setlocal noswapfile
  setlocal syntax=none
  setlocal bufhidden=delete
  " replace current buffer with ruby's output
  silent execute ":%! ruby " . src . " 2&gt;&amp;1 "
  " change back to the source buffer
  wincmd p
endfunction

vmap &lt;silent&gt; &lt;F7&gt; :call Ruby_eval_vsplit()&lt;cr&gt;
nmap &lt;silent&gt; &lt;F7&gt; mzggVG&lt;F7&gt;`z
imap &lt;silent&gt; &lt;F7&gt; &lt;ESC&gt;&lt;F7&gt;a
map &lt;silent&gt; &lt;S-F7&gt; &lt;C-W&gt;l:bw&lt;cr&gt;
imap &lt;silent&gt; &lt;S-F7&gt; &lt;ESC&gt;&lt;S-F7&gt;a
</code></pre>

<p>Select some ruby code and hit F7 or hit F7 to evaluate the entire buffer. A new split is automatically opened or it uses an existing split if one is available.</p>

<h3>Create a usable scratch buffer</h3>

<p>Now if you combine that with the <a href="http://vim.sourceforge.net/scripts/script.php?script_id=664">scratch.vim plugin</a> you have a nice little 1-2 punch combination of ruby prototyping bliss. Nub tip: download scratch.vim put into $VIMDIR\vimfiles\plugins\ restart your editor and type :Scratch then type :set ft=ruby to get ruby syntax highlighting in the scratch buffer.</p>

<p>I may be wrong but I think this stuff comes with the emacs ruby mode for free (scratch buffer is a built-in emacs feature). </p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2008/01/05/using-vim-as-an-interactive-ruby-environment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RubyCube on Ubuntu 7.10</title>
		<link>http://jrepp.com/2007/10/19/rubycube-on-ubuntu-710/</link>
		<comments>http://jrepp.com/2007/10/19/rubycube-on-ubuntu-710/#comments</comments>
		<pubDate>Fri, 19 Oct 2007 05:04:32 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[rubycube]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://jrepp.com/2007/10/19/rubycube-on-ubuntu-710/</guid>
		<description><![CDATA[I spent a few minutes on my new laptop with RubyCube. Since it uses GLUT as a foundation it was simple to port the extconf.rb to build on Ubuntu. I&#8217;m going to have to wait until after we ship TR &#8230; <a href="http://jrepp.com/2007/10/19/rubycube-on-ubuntu-710/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I spent a few minutes on my new laptop with RubyCube. Since it uses GLUT as a foundation it was simple to port the extconf.rb to build on Ubuntu.</p>

<p>I&#8217;m going to have to wait until after we ship TR before I do any of the real work that I want to get done on RubyCube.</p>

<p><a href="http://jrepp.com/?attachment_id=112" rel="attachment wp-att-112" title="rubycube-ubuntu">
<p style="text-align: center"><img src="http://jrepp.com/wp-content/uploads/2007/10/rubycube-ubuntu.thumbnail.png" alt="rubycube-ubuntu" /></p></p>

<p></a></p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2007/10/19/rubycube-on-ubuntu-710/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing a Finite State Machine with a Ruby Domain Specific Language</title>
		<link>http://jrepp.com/2007/08/14/implementing-a-finite-state-machine-with-a-ruby-domain-specific-language/</link>
		<comments>http://jrepp.com/2007/08/14/implementing-a-finite-state-machine-with-a-ruby-domain-specific-language/#comments</comments>
		<pubDate>Tue, 14 Aug 2007 09:12:21 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[austin]]></category>
		<category><![CDATA[game programming]]></category>
		<category><![CDATA[meetup]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://jrepp.com/2007/08/14/implementing-a-finite-state-machine-with-a-ruby-domain-specific-language/</guid>
		<description><![CDATA[DSL-FSM.. that kinda sounds like some wierd internet sub-culture. It stands for domain specific language &#8211; finite state machine. I proposed both topics as presentation material for the austin-ruby group that I meet with once a month. Steven Harms the &#8230; <a href="http://jrepp.com/2007/08/14/implementing-a-finite-state-machine-with-a-ruby-domain-specific-language/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>DSL-FSM.. that kinda sounds like some wierd internet sub-culture.  It stands for domain specific language &#8211; finite state machine. I proposed both topics as presentation material for the austin-ruby group that I meet with once a month. <a href="http://stevengharms.com">Steven Harms</a> the organizer recommended both/either so I combined it into one piece of code as it actually works pretty well that way.</p>

<p>The DSL that I&#8217;m using is pretty small right now, which lends itself to easier understanding and explanation.</p>

<p><a href="http://jrepp.com/code/rbfsm.tgz"> Ruby code tarball can be downloaded here. </a></p>

<p>A FSM is defined in a ruby script file without any class definition using the following rules:
<ol>
    <li>All attributes are specified in a method named &#8216;setup&#8217;. Setup takes an argument hash which may contain arguments that can be used to setup a FSM entity.</li>
    <li>All states are specified by defining top level methods with the name &#8216;while<em>&lt;statename&gt;&#8217;. These methods are called in a tick update while that state is active.</li>
    <li>All transitions are initiated by saying start :statename</li>
</ol>
For example the creature FSM is has a method:
<blockquote><strong>def while</em>idle</strong>
<blockquote><strong>target_nearest</strong></p>

<p><strong>start :chasing if @target</strong></blockquote>
<strong>end</strong></blockquote>
All FSM entity templates  can be loaded in the world using world.load(&#8216;template-name&#8217;). The world is currently driven by a simple script named &#8216;simulate.rb&#8217; which allows you to single step the world simulation and watch all the state machines make their choices. There are some debugging tools available. You can list all active entities and dump the world grid.</p>

<p>World#load uses the Object#instance_eval method to evaluate the contents of the FSM definition in terms of a FSM base instance. The FSM class defines some methods that can be called within the FSM definition to control state transitions and to access common methods.</p>

<p>Practically speak this is a very simple way to enable easy extension of a system. It provides an easier path to refactor the individual state machines and lowers the barrier to entry for writing state machine code. Additionally, it would be nice to include certain types of behavior from modules so that state machine authors could have easy access to some of the methods currently defined in creature FSM. This would include methods like target_nearest.Â  You could also mix in native C modules to get access to things like a path finding grid.</p>

<p>Ideas for playing with the code:
<ol>
    <li>Make creatures pick up the &#8216;ammo&#8217; entities</li>
    <li>Make creatures compete for the &#8216;fark&#8217; entities</li>
    <li>Add a new term to the FSM for state transitions. The method names should be named &#8216;when<em>changing</em>from<em>&lt;statename&gt;, when</em>changing<em>to</em>&lt;statename&gt;, when<em>changing</em>from<em>&lt;statename&gt;</em>to_&lt;statename&gt;&#8217; and should be executed when those state change patterns are matched.</li>
    <li>Allow entities to die</li>
</ol>
Some Notes:</p>

<p>A great article about some of the different types of DSL creation and the mindset from one of the coders at 37signals:</p>

<p><a href="http://weblog.jamisbuck.org/2006/4/20/writing-domain-specific-languages"> http://weblog.jamisbuck.org/2006/4/20/writing-domain-specific-languages</a></p>

<p>Careful of using missing_method, it bit me in the arse a number of times:</p>

<p><a href="http://redhanded.hobix.com/inspect/theBestOfMethod_missing.html"> http://redhanded.hobix.com/inspect/theBestOfMethod_missing.html</a></p>

<p>It&#8217;s really hard to track down bugs related to method<em>missing, any code you write inside an object implementing this needs to be carefully checked. It can also lead to blowing your stack when an error in method</em>missing recalls method_missing.. and on and on.</p>

<p>This little gem is nice to keep in your back pocket when trying to raise a descriptive exception:</p>

<p><a href="http://blog.nicksieger.com/articles/2006/09/06/rubys-exception-hierarchy"> http://blog.nicksieger.com/articles/2006/09/06/rubys-exception-hierarchy</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2007/08/14/implementing-a-finite-state-machine-with-a-ruby-domain-specific-language/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>RubyCube 0.2.1 released to RubyForge</title>
		<link>http://jrepp.com/2007/05/03/rubycube-021-released-to-rubyforge/</link>
		<comments>http://jrepp.com/2007/05/03/rubycube-021-released-to-rubyforge/#comments</comments>
		<pubDate>Thu, 03 May 2007 07:18:59 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[game programming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rubycube]]></category>

		<guid isPermaLink="false">http://jrepp.com/2007/05/03/rubycube-021-released-to-rubyforge/</guid>
		<description><![CDATA[A new windows binary and source distribution is ready on ruby forge with inital support for sprites.Â  I also took this opportunity to fix a few small bugs and update the documentation. This also marks the first public upload of &#8230; <a href="http://jrepp.com/2007/05/03/rubycube-021-released-to-rubyforge/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A new windows binary and source distribution is ready on ruby forge with inital support for sprites.Â  I also took this opportunity to fix a few small bugs and update the documentation. This also marks the first public upload of the master sources to ruby forge trunk. Although the sources are included in every release up to this point I have kept the main trunk version private but it&#8217;s now available for public download.</p>

<p>The sources in the distribution and on trunk can be built for Mac OS X for anyone who would like to experiment on that platform. Window start up time on my dual G5 is a bit slow for my tastes and I haven&#8217;t gotten in to optimize it yet.</p>

<p>I would like to thank basaah for his great suggestions and feedback on the 0.1.1 release.</p>

<p>I feel the code structure is straining a bit now that I&#8217;m starting to add in new objects.Â  It&#8217;s not terribly hard to add new functionality but the code base is definitely much larger than it was when I first threw this together as a proof of concept.</p>

<p>I&#8217;m going to do a dot release to document sprites and flush out the functionality. I&#8217;d love to get more feedback from anyone using RubyCube as to what you would like to see to make it more useful.</p>

<p>Since documentation is not yet ready for sprites the best way to see the API is in the new test/testsprite.rb driver.
<ul>
    <li><a href="http://rubyforge.org/frs/?group_id=3415" title="RubyCube downloads">Download available here</a></li>
    <li><a href="http://jrepp.com/rubycube_docs">Updated docs available here</a></li>
</ul></p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2007/05/03/rubycube-021-released-to-rubyforge/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RubyCube on Mac OS X</title>
		<link>http://jrepp.com/2007/04/17/rubycube-on-mac-os-x/</link>
		<comments>http://jrepp.com/2007/04/17/rubycube-on-mac-os-x/#comments</comments>
		<pubDate>Tue, 17 Apr 2007 04:53:04 +0000</pubDate>
		<dc:creator>proj</dc:creator>
				<category><![CDATA[macos]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rubycube]]></category>

		<guid isPermaLink="false">http://jrepp.com/2007/04/17/rubycube-on-mac-os-x/</guid>
		<description><![CDATA[I&#8217;ve been making small incremental progress. First problem I ran into was: objc: failed objc_getClass(NSObject) for GLUTApplication-&#62;isa-&#62;isa objc: please link appropriate classes in your program Trace/BPT trap This was pretty easily fixed by making sure to pass &#8216;-framework Foundation&#8217; to &#8230; <a href="http://jrepp.com/2007/04/17/rubycube-on-mac-os-x/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been making small incremental progress.</p>

<p>First problem I ran into was:</p>

<p>objc: failed objc_getClass(NSObject) for GLUTApplication-&gt;isa-&gt;isa
objc: please link appropriate classes in your program
Trace/BPT trap</p>

<p>This was pretty easily fixed by making sure to pass &#8216;-framework Foundation&#8217; to the linker.</p>

<p>The next issue I&#8217;ve run into and I don&#8217;t have a good solution for so far is the GLUT startup performance on OS X. According to Sampler most of the time spent is in glutInit. When I drill down into glutInit I see that it is spending all it&#8217;s time in HIDUpdateDeviceList which it calls once during __glutGetNumberOfMouseButtons and again in __glutLoadPrefs. This descends down into a long chain of methods that appear to build an internal dictionary of devices (connected HID devices?). It appears this process is painfully slow, at least on my sample configuration.</p>

<p>I want the graphics window to pop up immediately (if at all possible) and so I&#8217;m going to have to spend more time figuring out the internals of what is really going on here. I&#8217;m sure it&#8217;s possible to speed it up but at what cost of my personal time? I&#8217;m not yet ready to write a specific windowing layer for the Mac.</p>
]]></content:encoded>
			<wfw:commentRss>http://jrepp.com/2007/04/17/rubycube-on-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
