Created
September 3, 2013 13:22
-
-
Save pasberth/6423846 to your computer and use it in GitHub Desktop.
メソッドの引数は破壊しないで!!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # coding: utf-8 | |
| class Tuple | |
| def initialize(*xs) | |
| @xs = xs | |
| end | |
| def [] *args | |
| @xs[*args] | |
| end | |
| def to_s | |
| "(%s)" % @xs.map(&:to_s).join(', ') | |
| end | |
| end | |
| class Hoge | |
| # 破壊可能な属性 | |
| attr_accessor :fuga | |
| def to_s | |
| "hoge(%s)" % self.fuga | |
| end | |
| # こういう引数を破壊するメソッドやめて!! | |
| # def change!(hoge) | |
| # tmp = self.fuga | |
| # self.fuga = hoge.fuga | |
| # hoge.fuga = tmp | |
| # end | |
| end | |
| class HogeHogeTuple < Tuple | |
| # こうしてほしい | |
| def change_fuga! | |
| tmp = self[0].fuga | |
| self[0].fuga = self[1].fuga | |
| self[1].fuga = tmp | |
| true | |
| end | |
| end | |
| hoge1 = Hoge.new | |
| hoge1.fuga = 1 | |
| hoge2 = Hoge.new | |
| hoge2.fuga = 2 | |
| HogeHogeTuple.new(hoge1, hoge2).change_fuga! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment