ruby - 通过 ruby​​ 中的值属性选择哈希值

标签 ruby arrays algorithm performance hash

在 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

所以我的问题是:

有没有更好的方法来做到这一点而不涉及遍历整个散列?

请注意,我不能使用键值,因为在同一个散列中将有多个具有相同类型的对象(并且键值已经被用来表示其他东西)。

如果有一种简单的方法可以对数组执行此操作,那也可以(因为我可以轻松地将散列转换为数组)。

谢谢!

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

最佳答案

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

I am trying to design an efficient function that can get the average of the values of all of objects of a certain type within the hash

除非我误解了您的意思,否则这不是您发布的代码的作用。 :x 机器人的平均值是 21(有 3 个 :x 机器人,值为 525355 + 25 + 35 == 6565 除以 3 个机器人是 21 ),但是你的代码(和我的,因为我是根据你的代码建模的)打印 13

is there a better way to get only objects of type :x ?

是的。要选择元素,请使用 select 方法。

is there a better way to do this that does not involve looping through the entire hash?

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

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

关于ruby - 通过 ruby​​ 中的值属性选择哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743893/

相关文章:

ruby-on-rails - 提高此服务器代码的性能以查找域?

php - 如何加快处理多个大型数组的缓慢加载 PHP 页面?

c++ - 将数据(字符串或整数)添加到 char 数组

ruby-on-rails - Ruby - 按属性降序对对象数组进行排序

ruby-on-rails - 无法使用:text in typed_store

java - 合并 n 个列表并对数据进行排序,保持原始顺序/约束

php - 如何在centos中为Mcrypt安装库

android生成随机唯一的颜色代码

ruby - 要散列的二维数组

C++ 在编译时知道给定类型的对象数