【发布时间】:2013-10-23 20:21:51
【问题描述】:
我已经为桃树定义了一个类作为作业的一部分。我想知道是否可以在我的一种方法中包含一个 if 语句,以使树在 60 年后死亡。这是我的代码:
class Tree
def initialize(color="green", fruit="peaches", age=0, peaches_amount=0)
@color = color
@fruit = fruit
@age = age
end
#age increases by one year every year
def the_age
@age += 1
return @age
end
#yield of peaches increases by 5 peaches every year
def peaches
@peaches_amount += 5
return @peaches_amount
end
def death
if age <60 return "I am dead"
else
end
end
end
【问题讨论】:
-
当然可以。你的代码有什么问题?
-
你还会把它放在哪里?
-
else 语句中应该包含什么内容?
-
请注意,您的逻辑是倒退的,并且将规范地表示为
def death; return "I am dead" if age > 60; end或类似的。 -
我们无法回答有关您的应用功能的问题,因为我们并未开发您的应用。就我个人而言,我会有一个
dead?方法,如果年龄 > 60 则返回 true,否则返回 false。然后在需要检查一棵树是否死亡的地方使用该方法。
标签: ruby-on-rails ruby class if-statement methods