2016-04-25 57 views
-3

锻炼问题如下,我的答案。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

'的Rails = Ruby' –

+0

错字,这是凌晨两点我在哪里.. – whatabout11

+0

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

回答

2

据锻炼,你应该创建一个类Tree与单个属性rings和两个方法,bear_fruit?winter_season

    • 一个rings创建Tree类属性和吸气方法
    • a bear_fruit?方法其中
      • 返回true如果树具有超过7点的环,但小于15
      • 返回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 
+0

'(8..14).include?(@ rings)'是一种Rubyish和英语。 –

+0

@KeithBennett你也可以写'@ rings.between?(8,14)',但是这会导致代码和规范中的数字不同。 '@rings> 7 && @rings <15'类似*“超过7但小于15”*更接近IMO。 – Stefan

+0

你说的是真实的,但我会争辩说,在偏离字面上的规范中使用更人性化的符号是有价值的。 (虽然数字不同,但条件是相同的。)我认为我们认为在&& <术语中的事实是我们不得不使用C,C++和Java等相对较低级别的语言进行编程的事实,尽管短期内认知成本适度,但这种风格是值得的。 –

1

首先,它工作吗?我猜不是。运行它并查看错误是什么。

Ruby提供了多种循环方式,您可以在ruby docs中查找。如果我可以避免使用while循环,我宁愿不使用while循环,部分原因是使用break可能导致代码不可读。查看时间方法和其他枚举。