对不起,新手问题,大家好。这是:
我有一个看起来像这样的哈希:
{ "id" => { :task => [ { :due => Mon Dec 20 00:00:00 UTC 2010, completed: => "2010-12-18T17:29:57Z", :priority => "1", ... } ] , ... } , ... }
要对此进行排序,我使用:
tasks = hash.with_indifferent_access
tasks.sort_by { |k,v| [ v['task'][0]['completed'], v['task'][0]['due'], v['task'][0]['priority'] ] }
只要具有日期值,就可以正常工作。当它没有允许的日期值时,它看起来像这样:
:due => ""
然后我收到Rails错误说:“Array与Array的比较失败。”
我尝试将三元和其他逻辑设置为默认为远程日期,如果:due为空,但看起来这在sort_by块中是不可能的。
任何想法如何舔这个?非常感谢!
答案 0 :(得分:1)
这是一个示例,假设“due”是一个字符串,当为空时,您希望它在具有相同完成值的其他任务之前进行排序。我们的想法是将有效日期和空字符串转换为相同的可比数据类型(在这种情况下是自纪元以来的整数秒数)。我故意忽略了与您的问题无关的设置细节。
# Required for 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"}]