Tbpgr Blog

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

Ruby | Range | min

概要

Range#min -> object | nil
Range#min {|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).min
(2...5).min
(5..4).min
(hoge_min..hoge_max).min
(hoge_min..hoge_max).to_a
(hoge_min...hoge_max).min
(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).min                 # => 2
(2...5).min                # => 2
(5..4).min                 # => nil
(hoge_min..hoge_max).min   # =>     #<Hoge:0x00000600bdc170 @count=3>
(hoge_min..hoge_max).to_a  # => [   #<Hoge:0x00000600bdc170 @count=3>, #<Hoge:0x00000600bf7268 @count=4>, #<Hoge:0x00000600bf7240 @count=5>]
(hoge_min...hoge_max).min  # =>     #<Hoge:0x00000600bdc170 @count=3>
(hoge_min...hoge_max).to_a # => [   #<Hoge:0x00000600bdc170 @count=3>, #<Hoge:0x00000600bf6ac0 @count=4>]