Iterator pattern - Design Pattern in Ruby
複数の要素を持つオブジェクトが、それぞれの要素に順繰りにアクセスする方法を提供するパターン。
External iterator
has_next, next_item のような順繰りに必要なメソッドを提供することで、外部からの要素へのアクセスを可能にする。
loop処理などを自分で書く必要があるが、その分柔軟な記述が可能
Internal iterator
要素を引数にもったコードブロックを渡して、内部で各要素付きで実行してもらう。
簡潔に処理したいコードを書くことができる。
実装
eachを実装して、Enumerableをincludeするミニマムのコードを書いてみた。
class Player attr_reader :time def initialize (name, time) @name = name @time = time end def <=> (other) @time <=> other.time end end class PlayerGroup include Enumerable def initialize @players = [] end def add_player (player) @players << player end def each (&block) @players.each {|p| yield p} end end pg = PlayerGroup.new pg.add_player Player.new 'kiryuu', 10.0 pg.add_player Player.new 'bolt', 9.58 pg.add_player Player.new 'gatorin', 9.81 p pg.sort