Guest User

Untitled

a guest
Feb 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. {
  2. "firstName": "John",
  3. "lastName": "Smith",
  4. "age": 25,
  5. "address":
  6. {
  7. "streetAddress": "21 2nd Street",
  8. "city": "New York",
  9. "state": "NY",
  10. "postalCode": "10021"
  11. },
  12. "phoneNumber":
  13. [
  14. {
  15. "type": "home",
  16. "number": "212 555-1234"
  17. },
  18. {
  19. "type": "fax",
  20. "number": "646 555-4567"
  21. }
  22. ]
  23. }
  24.  
  25. h.select {|k,v| ["age", "address"].include?(k) }
  26.  
  27. class Hash
  28. def select_keys(*args)
  29. select {|k,v| args.include?(k) }
  30. end
  31. end
  32.  
  33. h.select_keys("age", "address")
  34.  
  35. hash.slice('firstName', 'lastName')
  36. # => { 'firstName' => 'John', 'lastName' => 'Smith' }
  37.  
  38. h = { "a" => 100, "b" => 200, "c" => 300 }
  39. h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
  40. h.select {|k,v| v < 200} #=> {"a" => 100}
  41.  
  42. h.select {|k,v| k == "age" || k == "address" }
  43.  
  44. hash = { a: true, b: false, c: nil}
  45. hash.except!(:c) # => { a: true, b: false}
  46. hash # => { a: true, b: false }
  47.  
  48. class Hash
  49. def select_keys(*args)
  50. filtered_hash = {}
  51. args.each do |arg|
  52. filtered_hash[arg] = self[arg] if self.has_key?(arg)
  53. end
  54. return filtered_hash
  55. end
  56. end
  57.  
  58. keys = [ "firstName" , "address" ]
  59. keys.zip(hash.values_at *keys).to_h
Add Comment
Please, Sign In to add comment