In our last installment, we had this code:

  def parenthesized_list(array)
    array.process_and_interpose("(", ",", ")") { |element| yield element }
  end

  class Array
    def process_and_interpose(initial, middle, last)
      inject_with_index(initial) do |memo, element, i|
        memo + yield(element) + (i != length - 1 ? middle : last)
      end
    end
  end

I’d extracted the latter method not because I thought I was likely to need it, but because I thought the original implementation of parenthesized_list was insufficiently evocative.

But then today I was finishing off the Ruby version of my CLI tool, so I needed to update entries in existing rows in SQL tables, instead of just adding new rows. And the syntax is different: instead of

INSERT INTO people (id, name, age) VALUES ('256', 'Fred', '25');

the syntax is

UPDATE people SET name = 'George', age = '36' WHERE id = '256';

Which seems like a rather gratuitous difference to me, though I admittedly don’t know SQL nearly well enough to know if there’s a good reason for it.

No parenthesized lists in sight, but that’s okay: my newly extracted process_and_interpose function does great!

  def update_string
    "UPDATE `#{@table.name}` SET #{assignments} WHERE `id` = #{id}"
  end

  def assignments
    @updates.to_a.process_and_interpose("", ",", "") do |assignment|
      "`#{assignment[0]}` = #{quote(assignment[1])}"
    end
  end

The Ruby version of the CLI tool seems to work fine now, incidentally. I haven’t flipped the switch yet and started using it for real, but as far as I can tell there’s no reason not to: it passes all the acceptance tests. (And they run faster than they did under Java; no idea why, but I’m pleasantly surprised.) There’s a bit of refactoring to do, and at some point I might want to think about what the implementation is telling me about my class hierarchies (or, indeed, about the differing importance of class hierarchies in dynamic and static languages), but all in all I’m quite happy.

Post Revisions:

There are no revisions for this post.