Created
October 11, 2016 11:00
-
-
Save ryosuke-endo/e62e1dfc50fd65ed77a4241b37105a18 to your computer and use it in GitHub Desktop.
This file contains 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 Family | |
def self.build | |
yield | |
end | |
end | |
x = Family.build do |family| | |
family.new_child('john') do |child| | |
child.hobby = 'game' | |
child.age = 18 | |
end | |
family.new_child('yamada') do |child| | |
child.hobby = 'study' | |
child.age = 12 | |
end | |
end | |
x.children |
ai-kadota
commented
Oct 11, 2016
•
途中で挫折
class Family
class Child
attr_writer :age, :hobby
end
attr_reader :children
def initialize
@childreb = []
end
end
family = Family.new
child = family.new_child('john')
child.hobby = 'game'
child.age = 18
family.new_child('yamada')
child.hobby = 'study'
child.age = 12
x.chilren
修正
class Family
attr_reader :children
def initialize
@children = []
end
def new_child(name)
child = Child.new(name)
@children << Child.new(name)
child
end
end
class Child
attr_writer :hobby, :age
def initialize(name)
@name = name
end
end
やり直した
class Family
attr_reader :children
class << self
def build
family = self.new
yield(family)
family
end
end
def initialize
@children = []
end
def new_child(name)
child = Child.new
yield(child)
@children << child
end
end
class Child
attr_writer :hobby, :age
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment