2013-10-23 56 views
0

我已經爲桃樹定義了一個類作爲任務的一部分。我想知道是否可以在我的一種方法中包含一個if語句,以使樹在60年後死亡。這是我的代碼:可以在ruby中的方法中包含if語句嗎?

class Tree 
    def initialize(color="green", fruit="peaches", age=0, peaches_amount=0) 
    @color = color 
    @fruit = fruit 
    @age = age 
    end 

#age increases by one year every year 
    def the_age 
    @age += 1 
    return @age 
    end 

#yield of peaches increases by 5 peaches every year 
    def peaches 
    @peaches_amount += 5 
    return @peaches_amount 
    end 

    def death 
    if age <60 return "I am dead" 
    else 
    end 
    end 
end 
+2

當然可以。你的代碼有什麼問題? – usha

+3

你會把它放在哪裏? –

+0

我會在else語句中包含什麼? – user2759592

回答

0

如果你嘗試:

tree = Tree.new 
tree.peaches 
  • 你得到一個錯誤undefined method '+' for nil:NilClass
  • 您從未定義過@peaches_amount
  • 您從未定義過age

在你的定義中,如果你年輕60歲,你就死了。我認爲你必須扭轉你的支票。

如果您已經死亡,您還可以檢查peaches

見我的例子:

class Tree 
    def initialize(color="green", fruit="peaches", age=0, peaches_amount=0) 
      @color = color 
      @fruit = fruit 
      @age = age 
      @peaches_amount = peaches_amount 
      @dead = false 
    end 
    #age increases by one year every year 
    def the_age 
      @age += 1 
      if @age == 60 
      @dead = true 
      puts "I died" 
      end 
      return @age 
    end 
    #yield of peaches increases by 5 peaches every year 
    def peaches 
     if @dead 
     return 0 
     else 
     return 5 * @age 
     end 
    end 

    def dead? 
     if @dead 
     return "I am dead" 
     else 
     return "I am living" 
     end 
    end 
    end 

tree = Tree.new 
puts "%i Peaches after %i years" % [ tree.peaches, tree.age ] 
30.times{ tree.the_age } 
puts "%i Peaches after %i years" % [ tree.peaches, tree.age ] 
30.times{ tree.the_age } 
puts "%i Peaches after %i years" % [ tree.peaches, tree.age ] 

輸出:

0 Peaches after 0 years 
150 Peaches after 30 years 
I died 
0 Peaches after 60 years 

給你一個真正的答案,你應該定義你想實現什麼。

0

檢查你的語法。不要將return "I am dead"與條件放在同一行上!

if @age > 60 
"I am dead" 
end 

你也可以這樣做:

"I am dead" if @ge > 60 

而且,你不需要在Ruby中明確的回報,至少在這種情況下,因爲最後計算語句的結果是該方法的返回值。

知道一件好事:您可以使用ruby -c my_script.rb來檢查是否有語法錯誤。或者一個好的IDE。

這是Ruby 101,所以我建議你閱讀一些好書或遵循一些教程,那裏有很多。

相關問題