Bechir Segni Bechir Segni - 1 year ago 57
Ruby Question

Search and extract results from an array based on an entry keyword in ruby

I would like to compare an Array to an element and extract those data in the another Array
Here is an example of data i'm working with:

Array = [{:id=>3, :keyword=>"happy", :Date=>"01/02/2016"},
{:id=>4, :keyword=>"happy", :Date=>"01/02/2016"} ... ]

for example i want the first keyword happy to search the same array ,extract if there's any similar words and put them inside another array here is what i'm looking for an end result:

Results = [{:keyword=>happy, :match =>{
{:id=>3, :keyword=>"happy", :Date=>"01/02/2016"}... }]

Here is the first part of the code :

def relationship(file)
data = open_data(file)
parsed = JSON.parse(data)
keywords = []
i = 0
parsed.each do |word|
keywords << { id: i += 1 , keyword: word['keyword'].downcase, Date: word['Date'] }

Answer Source
def search_keyword(keyword)
    hash = [
        {:id=>1, :keyword=>"happy", :Date=>"01/02/2015"},
        {:id=>2, :keyword=>"sad", :Date=>"01/02/2016"},
        {:id=>3, :keyword=>"fine", :Date=>"01/02/2017"},
        {:id=>4, :keyword=>"happy", :Date=>"01/02/2018"}
    keywords = []
    hash.each do |key|
        if key[:keyword] == keyword
            keywords << key
    #{:keyword=> keyword, :match=> keywords}


You could group the match elements by key (:match) then get the result with a single hash lookup.

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