【发布时间】:2016-04-25 08:37:39
【问题描述】:
下面的练习题是我的答案。
#Create a Tree class with a rings attribute and getter method.
#Trees create a ring for every winter that passes
#It should have a bear_fruit? method which should return true if the
#has fruit that year. the tree produces fruit when it has
#more than 7 rings but less than 15, but false otherwise.
#The class should also have an winter_season method that increases #rings attr by 1.
谁能就这段代码给我建设性的批评?
class Tree
attr_accessor :winters, :rings, :bear_fruit?
def initialize(winters, rings)
@winters = winters
@rings = rings
end
def rings_created
@winters = 0
@rings = 0
while @winters == @rings do
@winters +=1
@rings +=1
break if @winters == 100
end
end
end
def bear_fruit
if @rings > 6 || < 16
@bear_fruit? = true
else
@bear_fruit? = false
end
end
def winter_season
@winters = 0
@rings = 0
while @winters < @rings do
@winters +=1
@rings +=2
break if @winters == 100
end
end
end
end
【问题讨论】:
-
打错了,我现在是凌晨 2 点......
-
你不能创建像
@bear_fruit?这样的实例变量。它们不能像方法名称那样包含?。您在这里的缩进也无处不在。为了清楚地看到正在发生的事情并识别错误,拥有组织良好、有序的代码很重要。请记住,解决这些问题的最佳方法是开发简单的单元测试来表达您的代码应该做什么,然后返回并让代码正常工作。这就是test driven development或TDD的原理。 -
请努力正确格式化您的代码。其他读者也可能是凌晨 2 点 ;)
-
@margo 正要修复,但你打败了我。我保证在粘贴之前它看起来会更好;)
-
你应该在提交之前修复它,这就是预览的目的。马上,任何人都可以从格式中看出这不会按原样工作。编程最重要的是让它工作,然后担心改进它。这可能看起来很苛刻,但如果你证明你已经做出了适当的努力,你会得到更多的帮助。