Derek Derek - 1 year ago 114
Ruby Question

Ruby: Easiest Way to Filter Hash Keys?

I have a hash that looks something like this:

params = { :irrelevant => "A String",
:choice1 => "Oh look, another one",
:choice2 => "Even more strings",
:choice3 => "But wait",
:irrelevant2 => "The last string" }

And I want a simple way to reject all the keys that aren't choice+int. It could be choice1, or choice1 through choice10. It varies.

How do I single out the keys with just the word choice and a digit or digits after them?


Turn the hash into a string with tab (\t) as a delimiter. I did this, but it took several lines of code. Usually master Rubicians can do it in one or so lines.

Answer Source

You can use the select method. Note, you'll need to convert the key from a Symbol to a String to do the regexp match. This will give you a new Hash with just the choices in it.

choices = { |key, value| key.to_s.match(/^choice\d+/) }

or you can use delete_if and modify the existing Hash e.g.

params.delete_if { |key, value| !key.to_s.match(/choice\d+/) }

or if it is just the keys and not the values you want then you can do: { |key| key.to_s.match(/^choice\d+/) }

and this will give the just an Array of the keys e.g. [:choice1, :choice2, :choice3]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download