在Ruby中,我有一個哈希值的對象。每個對象都有一個類型和一個值。我試圖設計一個有效的函數,它可以得到散列內某個類型的所有對象的值的平均值。在ruby中通過value屬性選擇哈希值
下面是如何這是目前實施的示例:
#the hash is composed of a number of objects of class Robot (example name)
class Robot
attr_accessor :type, :value
def initialize(type, value)
@type = type
@value = value
end
end
#this is the hash that inclues the Robot objects
hsh = { 56 => Robot.new(:x, 5), 21 => Robot.new(:x, 25), 45 => Robot.new(:x, 35), 31 => Robot.new(:y, 15), 0 => Robot.new(:y, 5) }
#this is the part where I find the average
total = 0
count = 0
hsh.each_value { |r|
if r.type == :x #is there a better way to get only objects of type :x ?
total += r.value
count += 1
end
}
average = total/count
所以我的問題是:
有沒有更好的方式來做到這一點,不涉及在整個散列循環?
請注意,我不能使用鍵值,因爲在同一個散列中將會有多個具有相同類型的對象(並且鍵值正被用於表示其他事物)。
如果有一個簡單的方法來做到這一點與數組,這也將工作(因爲我可以輕鬆地將哈希轉換爲數組)。
謝謝!
編輯:修正了我的代碼錯誤。
感謝像鑰匙,我在我的代碼固定的錯誤。我沒有很強的統計數據證明這是導致性能瓶頸的原因,但我確信它是這樣,因爲這種方法在我的程序的每次迭代中被稱爲數百次。對於可以幫助我測試程序性能的工具或方法,您有任何建議嗎? – Andrew 2010-09-19 03:27:47