試してみると:
tree = Tree.new
tree.peaches
- エラーが発生します
undefined method '+' for nil:NilClass
。
- を定義することはありません
@peaches_amount
。
- を定義することはありません
age
。
あなたの定義では、60 歳未満の場合は死んでいます。チェックを取り消さなければならないと思います。
peaches
すでに死亡している場合もチェックインできます。
私の例を見てください:
class Tree
def initialize(color="green", fruit="peaches", age=0, peaches_amount=0)
@color = color
@fruit = fruit
@age = age
@peaches_amount = peaches_amount
@dead = false
end
#age increases by one year every year
def the_age
@age += 1
if @age == 60
@dead = true
puts "I died"
end
return @age
end
#yield of peaches increases by 5 peaches every year
def peaches
if @dead
return 0
else
return 5 * @age
end
end
def dead?
if @dead
return "I am dead"
else
return "I am living"
end
end
end
tree = Tree.new
puts "%i Peaches after %i years" % [ tree.peaches, tree.age ]
30.times{ tree.the_age }
puts "%i Peaches after %i years" % [ tree.peaches, tree.age ]
30.times{ tree.the_age }
puts "%i Peaches after %i years" % [ tree.peaches, tree.age ]
出力:
0 Peaches after 0 years
150 Peaches after 30 years
I died
0 Peaches after 60 years
本当の答えを得るには、実装したいものを定義する必要があります。