Q:

Adding data of an unknown type to a hash

Ruby seems like a language that would be especially well suited to solving this problem, but I'm not finding an elegant way to do it.  What I want is a method that will accept a value and add it to a hash like so, with specific requirements for how it is added if the key already exists:
Adding 'foo' to :key1
{:key1 => 'foo'}

Adding 'bar' to :key1
{:key1=> 'foobar'}

Adding ['foo'] to :key2
{:key2 = ['foo']}

Adding ['bar'] to :key2 
{:key2 => [['foo'], ['bar']]

Adding {:k1 => 'foo'} to :key3
{:key3 => {:k1 => 'foo'}}

Adding {:k2 => 'bar'} to :key3 
{:key3 => {:k1 => 'foo', :k2 => 'bar'}}

Right now I can do this but it looks sloppy and not like idiomatic Ruby.  What is a good way to do this?

A:

To make it more Ruby-like you might want to extend the Hash class to provide this kind of functionality across the board, or make your own subclass for this specific purpose. For instance:
class FancyHash < Hash
  def add(key, value)
    case (self[key])
    when nil
      self[key] = value
    when Array
      self[key] = [ self[key], value ]
    when Hash
      self[key].merge!(value)
    else
      raise "Adding value to unsupported #{self[key].class} structure"
    end
  end
end

This will depend on your exact interpretation of what "adding" means, as your examples do seem somewhat simplistic and don't address what happens when you add a hash to a pre-existing array, among other things.
The idea is that you define a handler that accommodates as many possibilities as reasonable and throw an exception if you can't manage.

