Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash remove all except specific keys

I would like to remove every key from a hash except a given key.

For example:

{  "firstName": "John",  "lastName": "Smith",  "age": 25,  "address":  {      "streetAddress": "21 2nd Street",      "city": "New York",      "state": "NY",      "postalCode": "10021"  },  "phoneNumber":  [      {        "type": "home",        "number": "212 555-1234"      },      {        "type": "fax",        "number": "646 555-4567"      }  ] } 

I want to remove everything except "firstName" and/or "address"

Thanks

like image 300
glarkou Avatar asked Jul 08 '11 03:07

glarkou


2 Answers

What about slice?

hash.slice('firstName', 'lastName')  # => { 'firstName' => 'John', 'lastName' => 'Smith' } 
like image 148
Mario Uher Avatar answered Sep 30 '22 14:09

Mario Uher


Some other options:

h.select {|k,v| ["age", "address"].include?(k) } 

Or you could do this:

class Hash   def select_keys(*args)     select {|k,v| args.include?(k) }   end end 

So you can now just say:

h.select_keys("age", "address") 
like image 36
Jake Dempsey Avatar answered Sep 30 '22 14:09

Jake Dempsey