在ruby中按value属性选择哈希值

And*_*rew 1 ruby arrays algorithm hash performance

在Ruby中,我有一个对象哈希.每个对象都有一个类型和一个值.我试图设计一个有效的函数,可以获得散列中特定类型的所有对象的平均值.

以下是当前如何实现此示例的示例:

#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
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

有没有更好的方法来做到这一点,不涉及循环整个哈希?

请注意,我不能使用键值,因为在同一个哈希中会有多个具有相同类型的对象(并且键值用于表示已经存在的其他内容).

如果有一种简单的方法可以使用数组,那也可以(因为我可以轻松地将哈希转换为数组).

谢谢!

编辑:我的代码中修复了错误.

Jör*_*tag 5

hsh.values.select {|v| v.type == :x}.map(&:value).reduce(:+) / hsh.size
Run Code Online (Sandbox Code Playgroud)

我试图设计一个有效的函数,可以获得散列中特定类型的所有对象的平均值

除非我误解了你想说的内容,否则这不是你发布的代码所做的.该平均值:x机器人是21(有3个:x机器人,其值5,2535; 5 + 25 + 35 == 65以及65由3个机器人分成21),但你的代码打印(和我,因为我之后你模仿我的)13.

是否有更好的方法来获得只有类型的对象:x?

是.要选择元素,请使用该select方法.

有没有更好的方法来做到这一点,不涉及循环整个哈希?

否.如果要查找具有给定属性的所有对象,则必须查看所有对象以查看它们是否具有该属性.

您是否有实际的统计证据证明方法会导致您的性能瓶颈?