eval
是邪惡的。不要使用它。這是一個等效的代碼,它應該適用於任何數量的分數。它使用a <=> b
返回-1
,0
或1
的事實。
您的輸入格式不是很方便。此代碼使用each_slice
並轉置將[1,2,3,4,5,6]
轉換爲[[1, 4], [2, 5], [3, 6]]
。然後,您可以遍歷遊戲來計算總分:
def calc_score(a, b)
[[0, 0], [1, 0], [0, 1]][a <=> b]
end
def solve(*scores)
size = scores.size
raise 'Need an even number of scores' unless size.even?
raise 'Need at least two scores' unless size > 0
scores.each_slice(size/2).to_a.transpose.inject([0, 0]) do |(a_total, b_total), (a, b)|
a_score, b_score = calc_score(a, b)
[a_total + a_score, b_total + b_score]
end
end
甚至更短:
def solve(*scores)
size = scores.size
raise 'Need an even number of scores' unless size.even?
raise 'Need at least two scores' unless size > 0
scores.each_slice(size/2).to_a.transpose.map do |a, b|
calc_score(a, b)
end.transpose.map{ |s| s.inject(:+) } # .map(&:sum) in Ruby 2.4
end
舉個例子:
solve(1, 2, 3, 4, 5, 6)
# [0, 3]
solve(2, 0, 0, 3)
# [1, 1]
binding.local_variable_get是你最好的朋友。 – Ilya
so so \t 'binding.local_variable_get'是安全的eval()? –
不是,它的安全局部變量獲取:) – Ilya