以下是我的答案中的练习题。
#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
答案 0 :(得分:2)
根据练习,您应该创建一个具有单个属性Tree
的课程rings
和两个方法bear_fruit?
和winter_season
:
- 创建一个
Tree
课程
rings
属性和getter方法- 一个
,则bear_fruit?
方法如果树的响铃数超过7但小于15
- 返回
true
- 返回
false
否则- 一种
winter_season
方法
- 将
rings
提高1
这就是全部。它并没有说树应该跟踪冬天,也没有提到任何循环。
以下是我将如何实现它:
class Tree
attr_reader :rings
def initialize
@rings = 0
end
def bear_fruit?
@rings > 7 && @rings < 15
end
def winter_season
@rings += 1
end
end
答案 1 :(得分:1)
First, does it work? I'm guessing not. Run it and see what the error is.
Ruby provides a number of ways of looping which you can look up in the ruby docs. I prefer not to use while loops if I can avoid it, partly because it can lead to less readable code with the use of break. Look up the times method and other enumerables.