Ruby 将最小值和最大值添加到poro数组

Ruby 将最小值和最大值添加到poro数组,ruby,Ruby,如何将min和max方法添加到poro数组中 我有一个叫做Sensor class Sensor ... end 我希望通过一系列传感器,能够发送消息 min 和 max >代码>根据2种不同的自定义方法来检索我认为的最小值和最大值。 我想我必须重写一些方法(就像我需要排序时那样),但我可以找到关于它的信息 谢谢。您可以使用 范例 > ["a", "bb", "ccc"].max_by {|word| word.length } # => "ccc" 因此,如果在Senso

如何将
min
max
方法添加到poro数组中

我有一个叫做
Sensor

class Sensor 
 ...
end

我希望通过一系列传感器,能够发送消息<代码> min <代码>和<代码> max >代码>根据2种不同的自定义方法来检索我认为的最小值和最大值。 我想我必须重写一些方法(就像我需要排序时那样),但我可以找到关于它的信息

谢谢。

您可以使用

范例

> ["a", "bb", "ccc"].max_by {|word| word.length } 
# => "ccc"
因此,如果在
Sensor
类中定义了
min
max
方法,则可以调用

array_of_sensors.max_by {|s| s.max } # Min can be done similarly
或者使用shorcut

array_of_sensors.max_by &:max

您很可能希望使用类似的模块:

class Sensor
  include Comparable

  def <=>(other)
    # Comparison logic here.
    # Returns -1 if self is smaller then other
    # Return 1 if self is bigger then other
    # Return 0 when self and other are equal
  end
end

我能问一下波罗斯是什么吗?谢谢你的回答。这似乎是最简单的方法。
class Sensor
  include Comparable

  def <=>(other)
    # Comparison logic here.
    # Returns -1 if self is smaller then other
    # Return 1 if self is bigger then other
    # Return 0 when self and other are equal
  end
end
class A
  attr_accessor :a

  include Comparable

  def initialize(a)
    @a = a
  end

  def <=>(other)
    self.a <=> other.a
  end
end

ary = [3,6,2,4,1].map{|a| A.new(a) }
ary.max       #=> #<A:0x000000027abc30 @a=6>