我如何通过创建和键值对来对此哈希进行排序

时间:2012-09-05 20:21:56

标签: ruby hash

嗨我很难做出这个哈希并通过创建和键值对来对它进行排序。

这是我的代码

 hash_answers = {}
 unless answers.blank?
  answers.each_with_index do |ans ,index|
    voted_up_users = ans.votes_up_by_all_users(ans)
    voted_down_users = ans.votes_down_by_all_users(ans)
    hash_answers[ans.id] = voted_up_users.count -voted_down_users.count #line one
    hash_answers[index+1] = ans.created_at # line 2
  end
end

如果我只在代码而不是第2行中使用第1行,则下面的代码对我来说很好

     @answers = hash_answers.sort_by { |key, value| value }.reverse

但我也想通过craeted_at

对其进行排序

我如何能够实现这一点或以其他方式制作哈希

任何帮助都将非常感谢

由于

2 个答案:

答案 0 :(得分:1)

answers.sort_by do |ans|
  [ans.net_votes, ans.created_at]
end

然后在你的答案课

def net_votes
  votes_up_by_all_users - votes_down_by_all_users
end

您不必像ans.votes_up_by_all_users(ans)那样将对象作为变量传递给自己。物体总是了解自己。

答案 1 :(得分:0)

通常,您可以通过创建这些内容的数组并将其用作排序键来对许多内容进行排序:

@answers = hash_answers.sort_by { |k, v| [ v[:created_at], v[:count] }

这取决于具有可开始的可排序结构。你把两个完全不同的东西塞进同一个哈希。更好的方法可能是:

hash_answers[ans.id] = {
  :id => ans.id,
  :count => voted_up_users.count -voted_down_users.count,
  :created_at => ans.created_at
}

您可以调整数组中元素的顺序,以正确的顺序排序。

相关问题