ruby - How to sort an array of class objects based on date? -
i have 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 sort array based on productavailabledatets
value, in descending order. tried doing following:
@products = @products.sort_by{ |k| -k['productavailabledatets'] }
but doing so, not able access productavailabledatets
field. tried print @products[0]['productavailabledatets']
. prints nil
. how can access field correctly?
if don't need data sorted database (assumed got data active record), can convert array , sort it:
@products.to_a.sort{ |a,b| b.productavailabledatets <=> a.productavailabledatets }
if array:
@products.sort{ |a,b| b.productavailabledatets <=> a.productavailabledatets }
edit: missed order. order implemented changing first , second parameter.
Comments
Post a Comment