如果你试试:
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
为了给你一个真正的答案,你应该定义你想要实现的东西。