0

嗨,我很难制作这个散列并通过 created of 和 key 、 value 对对其进行排序。

这是我的代码

 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

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

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

但我也想按 craeted_at 对其进行排序

我怎样才能做到这一点或以另一种方式制作散列

任何帮助将不胜感激

谢谢

4

2 回答 2

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

然后在你的 Answers 课上

def net_votes
  votes_up_by_all_users - votes_down_by_all_users
end

您不必像在ans.votes_up_by_all_users(ans). 对象总是了解自己。

于 2012-09-05T20:28:47.863 回答
0

Usually you can sort on a number of things by creating an array of these things and use that as your sort key:

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

This is dependent on having a sortable structure to start with. You're jamming two entirely different things into the same hash. A better approach might be:

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

You can adjust the order of the elements in the array to sort in the correct order.

于 2012-09-05T20:30:53.710 回答