the_
the_

Reputation: 1173

Sort hash based on keys matching with array

I have a rails 4 application. I have the following code:

@product_types = StoreProduct.where(:store_id => @store.id).pluck(:name)

@product_data = @products.map do |product|
    product[ :data ].values.reverse!
end

@product_types output looks like this: ["Color", "QTY", "TypeOf"]

@product_data output looks like this: [["RED", "17", "BOOK"]]

@products looks like: [#<Product id: 141, store_id: 146, data: {"Color"=>"RED", "QTY"=>"17", "TypeOf" => "BOOK"}>]

I want for @product_data to be sorted in the same order as @product_types. So if its QTY, Color, TypeOf as the @product_types, then the @product_data should be sorted by its keys in the same way as @product_types, so @product_data should be: 17, RED, BOOK.

Upvotes: 1

Views: 80

Answers (2)

seph
seph

Reputation: 6076

Instead of:

@product_data = @products.map do |product|
  product[:data].values.reverse!
end

try:

@product_data = @products.map do |product|
  @product_types.map { |pt| product[:data][pt] }
end

#=> [["RED", "17", "BOOK"]]

Upvotes: 2

kiddorails
kiddorails

Reputation: 13014

This might help. I am directly dealing with general Ruby constructs, mimic it for your @products:

foo = ["Color", "QTY", "TypeOf"]
bar = [{'QTY' => 17, 'TypeOf' => 'Book', 'Color' => 'Red'},
       {'Color' => 'Blue', 'QTY' => 18, 'TypeOf' => 'Gem'}]
p foo.map{ |x| bar.map { |y| y[x] } }.transpose 
#=> [["Red", 17, "Book"], ["Blue", 18, "Gem"]]

Running code.

Upvotes: 1

Related Questions