0

我有一系列问题,每个问题都有 acategory_id和 a value

我想映射这些,以便当category_id哈希中已经存在键 () 时,将这些值相加。

最后,我想在哈希中找到最大值:

h = Hash.new {|k, v| k[v] = 0}  

@test_session.answered_questions.each do |q|

  if h.key?(q.category_id)
     #add q.value to the value stored in the hash
  else
     h = { q.category_id => q.value } #insert the "q.category_id" as key and with value "q.value"
  end        

end

key_with_max_value = h.max_by { |k, v| v }[0] #find the highest value

@result.category = key_with_max_value
@result.score = h[key_with_max_value].value  

可能有更好的方法来实现这一点,但我对 Ruby 还是很陌生。

4

2 回答 2

3
h = Hash.new(0)
@test_session.answered_questions.each {|q| h[q.category_id] += q.value}
@result.category, @result.score = h.max_by { |k, v| v }

散列中的每个值都将被初始化为零,Hash.new(0)并且由于h.max_by返回键值对,您可以直接将它们分配给您的@result变量。

于 2012-12-11T15:52:48.927 回答
1

你可以简单地做:

@test_session.answered_questions.each { |q| h[q.category_id] += q.value }

当键不存在时,由于您初始化散列的方式,它被假定为具有值0,因此它被插入0 + q.value

请参阅文档,或尝试一下。

此外,您可以将用逗号分隔的两个变量分配给h.max_by { |k, v| v }. 这称为多重赋值,它也适用于数组:

a,b,c = [1,2,3]
于 2012-12-11T15:49:22.640 回答