Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Enumerable | minmax

概要

Enumerable#minmax

詳細

Enumerable#minmax <=>メソッドを利用して最小値と最大値を返します。
ブロックを指定した場合は、ブロックの評価結果で判定を行います。

サンプル

コード
# encoding: utf-8
class Person
  include Enumerable
  attr_accessor :name, :age
  def initialize(name, age)
    @name, @age = name, age
  end

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

persons = [Person.new("tanaka", 20), Person.new("sato", 55), Person.new("suzuki", 77)]

p persons
p persons.minmax
p persons.minmax {|one, other|one.age <=> other.age}
出力
[#<Person:0x2775c18 @name="tanaka", @age=20>, #<Person:0x2775bd0 @name="sato", @age=55>, #<Person:0x2775b88 @name="suzuki", @age=77>]
[#<Person:0x2775bd0 @name="sato", @age=55>, #<Person:0x2775c18 @name="tanaka", @age=20>]
[#<Person:0x2775c18 @name="tanaka", @age=20>, #<Person:0x2775b88 @name="suzuki", @age=77>]