ruby Hash.select 1.8.7 and 1.9.3 simultaneously compatible

In ruby 1.8.7, Hash.select produces an array of key/value pairs, one for each block that return strue.

In ruby 1.9.x, Hash.select produces a hash, including key/values for each block that returns true.

The 1.9.x behavior is actually a lot more useful, it’s usually what I wanted anyway.

But what if you need to select a sub-hash in code that needs to work in both 1.8.7 and 1.9.x?

Here’s one way to do it:

Hash[  some_hash.select {|k, v| wanted?(k,v)  ]

In both 1.8.7 and 1.9.x, Hash[] , if given a single array of pairs as an argument, will convert it to a Hash (although the 1.8.7 rdoc doesn’t actually say that, it appears to be true), and if given a Hash as an argument, will…. well, create a new Hash with the same contents, which is probably okay. (Otherwise, you’d have to use a couple of lines and an `unless return_value.kind_of? Hash` I guess).

So, even in purely 1.8.7 code,  Hash[] is also one way to use 1.8.7 Hash#select to create a sub-hash, what you probably wanted all along.

About these ads
This entry was posted in General. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s