Sig
Sig

Reputation: 5986

Add min and max to array of POROs

How can I add min and max methods to an array of POROs?

I have a class called Sensor

class Sensor 
 ...
end

And I wish to, given an array of sensors, be able to send the message min and max to retrieve what I consider the minimum and the maximum according to 2 different custom methods.

I suppose I have to override some methods (as I do when I need sorting) but I can find information about it.

Thanks.

Upvotes: 0

Views: 47

Answers (2)

BroiSatse
BroiSatse

Reputation: 44715

Most likely you want to use Comparable module:

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

Having this in place you can compare sensors with operators like >, <, <=. You can also sort an array of such the objects and use max and min methods.

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>

Upvotes: 1

Santhosh
Santhosh

Reputation: 29144

You can use max_by and min_by methods

array_of_objects.max_by { |x| x.custom_method_in_object }

example

> ["a", "bb", "ccc"].max_by {|word| word.length } 
# => "ccc"

So, if you have min and max methods defined in Sensor class, you can call

array_of_sensors.max_by {|s| s.max } # Min can be done similarly

or using the shorcut

array_of_sensors.max_by &:max

Upvotes: 0

Related Questions