Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

Ruby | Enumerable | min_by

概要

Enumerable#min_by

詳細

Enumerable#min_by ブロックの評価結果で判定を行い最小値を返します

サンプル

コード
# 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.min_by{|person|person.name}
p persons.min_by{|person|person.age}
p persons.min_by(&:name)
p persons.min_by(&:age)
出力
[#<Person:0x2455998 @name="tanaka", @age=20>, #<Person:0x2455950 @name="sato", @age=55>, #<Person:0x2455908 @name="suzuki", @age=77>]
#<Person:0x2455950 @name="sato", @age=55>
#<Person:0x2455998 @name="tanaka", @age=20>
#<Person:0x2455950 @name="sato", @age=55>
#<Person:0x2455998 @name="tanaka", @age=20>