Ruby, iOS, and Other Development

A place to share useful code snippets, ideas, and techniques

All code in posted articles shall be considered public domain unless otherwise noted.
Comments remain the property of their authors.

2007-01-22

The Dread Comma

Consider the following scrap of code from a Rails helper method:

  hash = { :id => result.id,
    :title => result.name,
    :addr => result.foo }
  hash[:foo] = controller.send(:render_to_string, {:partial => "foo", :object => hash}),
  hash.merge!(more_params(result))
  hash.to_json

That code raises a JSON::CircularDatastructure exception. Here is the corrected code:

  hash = { :id => result.id,
    :title => result.name,
    :addr => result.foo }
  hash[:foo] = controller.send(:render_to_string, {:partial => "foo", :object => hash})
  hash.merge!(more_params(result))
  hash.to_json

The difference is a single comma at the end of the fourth line. Without that comma, the code works as expected. In sequence, a literal hash is declared, an additional key-value pair is added, and a hash returned by a method call is merged in. With the comma, however, hash[:foo] is set to a two-element array. The first element is what we intended and the second is the hash itself, creating a recursive (a.k.a. circular) data structure. I am too embarassed to admit how long it took me to figure out what was going on.

Forewarned, may you never encounter such a bug in your own code. Enjoy!

Labels: , ,

1 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home