鍛鍊問題如下,我的答案。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