Ruby OOP正确的概念?

时间:2016-04-25 08:37:40

标签: 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

2 个答案:

答案 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.