Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created November 9, 2011 11:43
Show Gist options
  • Select an option

  • Save pasberth/1351204 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1351204 to your computer and use it in GitHub Desktop.
コンストラクタでの初期化の一部を肩代わりしてくれるdefinit.rb
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