Mr eel

HashWithIndifferentAccess is the annoying kind of hash

Well, not always. Generally while using Rails you won’t notice this particular class. Rather you’re happily chucking strings and symbols into the params. It works so, no need to worry.

I ran into something a bit annoying today though. I decided to use HashWithIndifferentAccess over an ordinary Hash in a library I was writing. Mainly so I didn’t have to worry about users trying to access the contents of the hash by passing in strings or symbols — dealing with params and flash has meant Rails devs come to expect that behavior all over the place. Not complaining, but there it is.

Anyhow, the annoying bit is that HWIDA doesn’t accept a block when you initialize it — unlike a regular Hash. I do this so I can have the default value of a entry in the hash be an array.

Like so:

	my_hash = Hash.new {|hash, key| hash[key] == []}

Then we can happily append elements to the array in an entry without having to check that it’s there and create it.

	my_hash[:entry] < < :into_the_array_with_gusto!

That’s just lovely. Sadly HWIDA doesn’t do this. It just ignores the block. So trying to do the above:

	my_hash = HashWithIndifferentAccess.new {|hash, key| hash[key] == []}
	my_hash[:entry] < < :into_the_array_with_gusto!

Gives me:

	NoMethodError: You have a nil object when you didn't expect it!
	You might have expected an instance of Array.
	The error occured while evaluating nil.< <

So I cry. Something to watch out for! It’s actually got me thinking I might actually write a patch that makes it accept a block, or perhaps just a sub class for my own use.

* thinks…

Posted on November 30th, 2006 | There are 0 comments

Comments

Add a comment

All contents © 2005—2007 Luke Matthew Sutton