Reputation: 7280
I have the following array of hashes:
@products = {#<ProductProxy:0xb486d148 @pA={"productAvailableDateTs"=>"2013-12-04T23:07:12.592Z", "mPrice"=>, "pStock"=>, "id"=>, "productId"=>, "productDesignerId"=>}>,
#<ProductProxy:0xb4adf304 @pA={"productAvailableDateTs"=>"2013-1-04T23:07:12.592Z", "mPrice"=>, "pStock"=>, "id"=>, "productId"=>, "productDesignerId"=>}>,
#<ProductProxy:0xb4adecec @pA={"productAvailableDateTs"=>"2013-15-03T23:07:12.592Z", "mPrice"=>, "pStock"=>, "id"=>, "productId"=>, "productDesignerId"=>}>,
...
}
I want to sort the array based on productAvailableDateTs
value, in descending order. I tried doing the following:
@products = @products.sort_by{ |k| -k['productAvailableDateTs'] }
But doing so, I am not able to access the productAvailableDateTs
field. i tried to print @products[0]['productAvailableDateTs']
. But it prints nil
. How can I access the field correctly?
Upvotes: 1
Views: 73
Reputation: 2555
If you don't need the data to be sorted by the database (assumed that you got that data from active record), you can convert it into an array and then sort it:
@products.to_a.sort{ |a,b| b.productAvailableDateTs <=> a.productAvailableDateTs }
If it is already an array:
@products.sort{ |a,b| b.productAvailableDateTs <=> a.productAvailableDateTs }
Edit: missed the order. The order is implemented by changing the first and second parameter.
Upvotes: 1