锻炼问题如下,我的答案。Ruby OOP正确的概念?
#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
'的Rails = Ruby' –
错字,这是凌晨两点我在哪里.. – whatabout11
你不能让实例变量,比如''@bear_fruit!?。他们不能像方法名称那样在其中包含'?'。这里的缩进也是遍布各地的。为了清楚地看到发生的事情和发现错误,有条理的,有序的代码是很重要的。记住解决这些问题的最好方法是开发简单的单元测试来表示代码应该执行的操作,然后返回并使代码正常工作。这是[测试驱动开发](https://en.wikipedia.org/wiki/Test-driven_development)或TDD的原则。 – tadman