Extract Keys and Values ​​from a Table Hash

advertisements

I have an hash like this -

    {"examples"=>
      [{"year"=>1999,
            "provider"=>{"name"=>"abc", "id"=>711},
            "url"=> "http://example.com/1",
            "reference"=>"abc",
            "text"=> "Sample text 1",
            "title"=> "Sample Title 1",
            "documentId"=>30091286,
            "exampleId"=>786652043,
            "rating"=>357.08115},
        {"year"=>1999,
            "provider"=>{"name"=>"abc", "id"=>3243},
            "url"=> "http://example.com/2",
            "reference"=>"dec",
            "text"=> "Sample text 2",
            "title"=> "Sample Title 2",
            "documentId"=>30091286,
            "exampleId"=>786652043,
        "rating"=>357.08115},
        {"year"=>1999,
            "provider"=>{"name"=>"abc", "id"=>191920},
            "url"=> "http://example.com/3",
            "reference"=>"wer",
            "text"=> "Sample text 3",
            "title"=> "Sample Title 3",
            "documentId"=>30091286,
            "exampleId"=>786652043,
        "rating"=>357.08115}]
}

and I would like to create a new array by pulling out the keys, and values for just the "text", "url" and "title" keys like below.

   [
     {"text"=> "Sample text 1", "title"=> "Sample Title 1", "url"=> "http://example.com/1"},
     {"text"=> "Sample text 2", "title"=> "Sample Title 2", "url"=> "http://example.com/2"},
     {"text"=> "Sample text 3", "title"=> "Sample Title 3", "url"=> "http://example.com/3"}
   ]

Any help is sincerely appreciated.


You should do as

hash['examples'].map do |hash|
    keys = ["text", "title", "url"]
    keys.zip(hash.values_at(*keys)).to_h
end

If you are below < 2.1 use,

 Hash[keys.zip(hash.values_at(*keys))]