I have a product parsed from a .csv file, it is stored in an array of hashes. In fact, this article number article .

 data = [{:article=>"MGXG-15"}] 

I have a description of the product, parsed from the xml page, which is also stored in an array of hashes. There is the same article number.

 products = [{:article=>"MGXG-15", :title=>"Консоль Kilan", :price=>"38290.0"}, {:article=>"eh_06", :title=>"Диван Juco", :price=>"145000.0"}, {:article=>"LSP-9197", :title=>"Светильник настенный", :price=>"44800.0"}] 

Tell me how to find the same article number in the products article number article from data and load the missing data accordingly (in the third variable for example).

    1 answer 1

    It is possible, if possible, to get rid of unnecessary copying of objects. Computer is faster not to "add", and "replace more complete."

    If all data hashmaps have a key :article , then you can naively choose the appropriate ones as follows:

     data.map do |data_element| # O(data.length) article = data_element[:article] products.find { |product| product[:article] == article } # O(products.length) end 

    If products long, it makes sense to pre-index it by :article :

     products_index = products.each_with_object({}) do |product, index| index[product[:article]] = product end 

    ... and instead of products_find { ... } use products_index[article] ( O(1) ).

    If you need to add anyway, instead of map do each , and inside, add attributes directly to the data_element with the help of merge! .

    • I have three part numbers in the .csv file. And indeed, when I go through data.map , I get three hashes. But not those! And three identical - the first hash, which is in the variable products repeated three times. But at the same time in the article are the necessary articles. - Andrey
    • [{:article=>"MGXG-15", :title=>"Консоль Kilan", :price=>"38290.0"}, {:article=>"MGXG-15", :title=>"Консоль Kilan", :price=>"38290.0"}, {:article=>"MGXG-15", :title=>"Консоль Kilan", :price=>"38290.0"}] This turns out when I data.map through data.map - Andrey
    • And you need to search for those articles that are in the variable article . I understand the point in the line @products.find { |product| product[:item] } @products.find { |product| product[:item] } - Andrey
    • @Chumak there really was a cant :) Now I corrected it, but try to debug it for your own interest, not looking in return. - D-side
    • Thank you very much, everything works) But I didn’t quite understand how indexing works in this case. - Andrey