Class: Systemdy::Utility::KeyValueFilter

Inherits:
Object
  • Object
show all
Defined in:
lib/systemdy/utility/key_value_filter.rb

Overview

Allows to filter a key/value dataset

Class Method Summary collapse

Class Method Details

.filter_by_keys(hash, *list_of_keys) ⇒ Hash

a method for filter an hash with a list of provided keys

Examples:

a very large hash to filter

tasks = { task_one: 'learn ruby', task_two: 'learn rspec', task_three: 'create a good documentation', ... } 

hash filtered with provided keys

filtered_hash = Systemdy::Utility::KeyValueFilter.filter_by_keys(tasks, 'task_one', 'task_two')
#=> {"task_one"=>"learn ruby", "task_two"=>"learn rspec"}

Parameters:

  • hash (Hash)

    the hash to filter

  • list_of_keys (Array)

    the list of keys to extract from the hash

Returns:

  • (Hash)

    a new hash that contains only the required keys



16
17
18
19
20
21
22
23
# File 'lib/systemdy/utility/key_value_filter.rb', line 16

def self.filter_by_keys(hash, *list_of_keys)
    # convert all hash keys from :key to "key"
    hash_keys_converted_into_string      = Hash[hash.map{ |key, value| [key.to_s, value] }] 
    # convert array elements from ":key" to "key"
    array_elements_converted_into_string = list_of_keys.flatten.map { |element| element.start_with?(':') ? element.gsub(':','') : element }
    # return an hash with only provided keys 
    hash_keys_converted_into_string.slice(*array_elements_converted_into_string) 
end