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 |
class Family
@@children = []
def new_child(name)
@@children << Child.new(name)
end
def children
@@children
end
end
class Child
attr_writer :hobby, :age
def initialize(name)
@name = name
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
family.children
class Family
attr_reader :children
class Child
attr_writer :name, :age, :hobby
end
def initialize
@children = []
end
def new_child(name)
child = Child.new
child.name = name
@children << child
child
end
end
途中で挫折
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
$ ruby hoge.rb
'hoge.rb:9:in
block in <main>': undefined method
new_child' for nil:NilClass (NoMethodError)from hoge.rb:3:in
build' from hoge.rb:7:in
minoshimashinichi-no-MacBook-Air:sr
1 class Family
2 def self.build
3 yield
4 end
5 end
6
7 # nil class?!
8 x = Family.build do |family|
9
10 family.new_child('john') do |child|
11 child.hobby = 'game'
12 child.age = 18
13 end
14
15 family.new_child('yamada') do |child|
16 child.hobby = 'study'
17 child.age = 12
18 end
19
20 end
21
22 x.children