Created
November 9, 2011 11:43
-
-
Save pasberth/1351204 to your computer and use it in GitHub Desktop.
コンストラクタでの初期化の一部を肩代わりしてくれるdefinit.rb
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
| class Class | |
| def definit *params, &initialize | |
| define_method :initialize do |*args, &blk| | |
| until params.empty? | |
| instance_variable_set :"@#{params.shift.to_sym}", args.shift | |
| end | |
| initialize && instance_exec(*args, &initialize) | |
| end | |
| end | |
| end | |
| class Person | |
| attr_reader :name, :age, :sex, :type | |
| definit :name, :age, :sex do |type| | |
| @type = type || !@sex | |
| end | |
| def to_s | |
| "#@name #@age #@sex #@type" | |
| end | |
| end | |
| Mana = Person.new 'mana', 18, true | |
| puts Mana |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment