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


i compare array element , extract data in array here 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 want first keyword happy search same array ,extract if there's similar words , put them inside array here i'm looking end result:

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

here first part of code :

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

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 |key|         if key[:keyword] == keyword             keywords << key         end     end     keywords     #{:keyword=> keyword, :match=> keywords} end  search_keyword('fine') #search_keyword('sad') 

you group match elements key (:match) result single hash lookup.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -