# 関数ではなくてクラスでクロージャを作る。 _published: 2010/04/08_ ![alt](http://b.hatena.ne.jp/entry/image/http://d.hatena.ne.jp/shunsuk/20100408/1270715018) Rubyでやります。まずは、一般的なクロージャ。 ```ruby def make_counter(cnt) lambda { cnt += 1 } end counter = make_counter(0) puts counter.call #=> 1 puts counter.call #=> 2 puts counter.call #=> 3 counter2 = make_counter(10) puts counter2.call #=> 11 puts counter2.call #=> 12 puts counter2.call #=> 13 ``` `make_counter` が返す無名関数の中に、 `cnt` が閉じ込められていますね。 それでは、本題。無名関数の代わりに匿名クラスを使います。 ```ruby def Counter(cnt) Class.new do define_method(:count) do cnt += 1 end end end class MyCounter < Counter(0) end counter = MyCounter.new puts counter.count #=> 1 puts counter.count #=> 2 puts counter.count #=> 3 class MyCounter2 < Counter(10) end counter2 = MyCounter2.new puts counter2.count #=> 11 puts counter2.count #=> 12 puts counter2.count #=> 13 ``` これだと、countメソッドに閉じ込めてるんじゃないかと思われるかもしれません。では、下のコードを。 ```ruby class MyCounter3 < Counter(0) end puts MyCounter3.new.count #=> 1 puts MyCounter3.new.count #=> 2 puts MyCounter3.new.count #=> 3 ``` 確かにクラスに閉じ込められてますね。 関数のクロージャの場合は、グローバル変数が不要になります。オブジェクト指向のメソッドだと、インスタンス変数ですね。これに対して、クラスのクロージャだと、クラス変数が不要になります。 ご利用は計画的に!