From: Shin-ichro Hara Date: 1998-11-25T01:36:46+09:00 Subject: [ruby-list:11043] enumerable.rb 原です。 Enumerable モジュールを書いてみました。Enumerable は組み込み で既に存在するので、これ自体は無用のもの。:-) ところでマニュアルの enum.html で grep(pattern) {|item|...} item === patternが成立する全ての要素を含む配列を返します というのは、pattern === item の間違いですよね。 -----^ enumerable.rb module Enumerable def collect ary = [] each { |x| ary.push yield(x) } ary end def each_with_index i = 0 each { |x| yield(x, i) i += 1 } end def find r = nil each { |x| if yield(x) r = x break end } r end def find_all ary = [] each { |x| ary.push(x) if yield(x) } ary end def grep(r) if iterator? each { |x| yield(x) if r === x } else ary = [] each { |x| ary.push(x) if r === x } ary end end def member?(a) r = false each { |x| if x == a r = true break end } r end def include?(a) member?(a) end def index(a) i = 0 j = nil each { |x| if x == a j = i break end i += 1 } j end def length i = 0 each { |x| i += 1 } i end def size length end def max m = nil if iterator? each { |x| m = x if !m || yield(x, m) > 0 } else each { |x| m = x if !m || (x <=> m) > 0 } end m end def min m = nil if iterator? each { |x| m = x if !m || yield(x, m) < 0 } else each { |x| m = x if !m || (x <=> m) < 0 } end m end def reverse ary = [] each { |x| ary.unshift x } ary end def _qsort(a, first, last) x = a[(first + last)/2] i, j = first, last loop do i+=1 while a[i] < x j-=1 while x < a[j] break if i >= j t = a[i] a[i] = a[j] a[j] = t i+=1 j-=1 end _qsort(a, first, i-1) if first < i-1 _qsort(a, j+1, last) if j+1 < last end private :_qsort def sort ary = to_a len = ary.length if iterator? _qsort_i(ary, 0, len-1) { |a, b| yield(a, b) } else _qsort(ary, 0, len-1) end ary end def to_a ary = [] each { |x| ary.push x } ary end end -----$ enumerable.rb