sorry newb question, everyone. here is:
i have hash looks this:
{ "id" => { :task => [ { :due => mon dec 20 00:00:00 utc 2010, completed: => "2010-12-18t17:29:57z", :priority => "1", ... } ] , ... } , ... }
to sort this, use:
tasks = hash.with_indifferent_access tasks.sort_by { |k,v| [ v['task'][0]['completed'], v['task'][0]['due'], v['task'][0]['priority'] ] }
this works fine long :due has date value. when doesn't have date value, permitted, looks this:
:due => ""
then rails error saying: "comparison of array array failed."
i tried putting in ternary , other logic default distant date if :due empty, seems isn't possible in sort_by block.
any ideas how lick one? many thanks!
here example assuming "due" string , when empty want sort before other tasks same completion value. idea convert both valid dates empty strings same comparable data type (in case integer number of seconds since epoch). have intentionally ignored details of setup irrelevant question.
# required time.parse require 'time' tasks = [ { completed: "2010-12-18t17:29:57z", due: "mon dec 20 00:00:00 utc 2010", priority: "1" },{ completed: "2010-12-18t17:29:57z", due: "mon dec 20 00:00:00 utc 2010", priority: "2" },{ completed: "2010-12-18t17:29:57z", due: "", priority: "1" },{ completed: "2010-12-17t17:29:57z", due: "mon dec 20 00:00:00 utc 2010", priority: "1" },{ completed: "2010-12-19t17:29:57z", due: "mon dec 20 00:00:00 utc 2010", priority: "1" } ] require 'pp' pp tasks.sort_by{ |h| [ time.parse(h[:completed]), h[:due].empty? ? 0 : time.parse(h[:due]).to_i, h[:priority].to_i ]} #=> [{:completed=>"2010-12-17t17:29:57z", #=> :due=>"mon dec 20 00:00:00 utc 2010", #=> :priority=>"1"}, #=> {:completed=>"2010-12-18t17:29:57z", :due=>"", :priority=>"1"}, #=> {:completed=>"2010-12-18t17:29:57z", #=> :due=>"mon dec 20 00:00:00 utc 2010", #=> :priority=>"1"}, #=> {:completed=>"2010-12-18t17:29:57z", #=> :due=>"mon dec 20 00:00:00 utc 2010", #=> :priority=>"2"}, #=> {:completed=>"2010-12-19t17:29:57z", #=> :due=>"mon dec 20 00:00:00 utc 2010", #=> :priority=>"1"}]
Comments
Post a Comment