Array of Hashes push into another Array

  • A+

I've an array contains hashes, I want to filter few parameters from the hash and insert the filtered data in another array but am not succeed below is the sample data I've used

a = a = [   {"name"=>"hello", "age"=>"12", "sex"=> "M", "city"=>"Chennai"},   {"name"=>"name2", "age"=>"26", "sex"=> "M", "city"=>"Banglore"} ] line_item = hash_data = {}  a.each do |datas|   hash_data[:name] = datas["name"]   hash_data[:age] = datas["age"]   line_item << hash_data end 

I am getting this result:

[   {:name=>"name2", :age=>"26"},   {:name=>"name2", :age=>"26"} ] 

But am expecting this:

[   {:name=>"hello", :age=>"12"},   {:name=>"name2", :age=>"26"} ] 

Somebody please help to sort out this, Thanks in advance

You can get the expected result with a combination of map and slice

a = [   {"name"=>"hello", "age"=>"12", "sex"=> "M", "city"=>"Chennai"},   {"name"=>"name2", "age"=>"26", "sex"=> "M", "city"=>"Banglore"} ]{ |e| e.slice("name", "age") } #=> [{"name"=>"hello", "age"=>"12"}, {"name"=>"name2", "age"=>"26"}] 
  • map: Returns Array containing the values returned by block
  • slice: Returns Hash including only the specified keys


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: