2016-04-25 56 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可能導致代碼不可讀。查看時間方法和其他枚舉。