Tbpgr Blog

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

Ruby | Range | max

概要

Range#max -> object | nil
Range#max {|a, b| ... } -> object | nil

詳細

範囲内の最大の値を返却。
範囲に要素がなければ nil

ブロック付の場合、
ブロックの評価結果で範囲内の各要素の大小判定を行い、最大の要素を返却。
範囲に要素がなければ nil

サンプルコード
require 'tbpgr_utils'

class Hoge
  attr_accessor :count

  def initialize(count)
    @count = count
  end

  def succ
    copy = self.dup
    copy.count += 1
    copy
  end

  def <=>(other)
    @count <=> other.count
  end
end

hoge_min = Hoge.new(3)
hoge_max = Hoge.new(5)

bulk_puts_eval binding, <<-EOS
(2..5).max
(2...5).max
(5..4).max
(hoge_min..hoge_max).max
(hoge_min..hoge_max).to_a
(hoge_min...hoge_max).max
(hoge_min...hoge_max).to_a
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

(2..5).max                 # => 5
(2...5).max                # => 4
(5..4).max                 # => nil
(hoge_min..hoge_max).max   # =>     #<Hoge:0x00000600bdc670 @count=5>
(hoge_min..hoge_max).to_a  # => [   #<Hoge:0x00000600bdc698 @count=3>, #<Hoge:0x00000600bf3780 @count=4>, #<Hoge:0x00000600bf3758 @count=5>]
(hoge_min...hoge_max).max  # =>     #<Hoge:0x00000600bf32d0 @count=4>
(hoge_min...hoge_max).to_a # => [   #<Hoge:0x00000600bdc698 @count=3>, #<Hoge:0x00000600bf2f38 @count=4>]