2012-11-15 88 views
0

我建立一個班的母親是「動物」,並建立一個孩子班。 我做的繼承順序是從子類到媽媽級但蹊蹺的在我的代碼,我必須解決這個問題,但不是很好,請幫助我,我是新手我的ruby代碼是語法錯誤請幫幫我

class Animal 
def initialize 
    @name = "DigDok" 
    @age = 20 
    @sex = "male" 
end 
end 
module Detail 
def detail_set 
    @detail.join(',') 
end 
    class Bird < Animal 
     def initialize 
      @detail = { 
       :wing => 2 
       :legs => 2 
      } 
     end 
    end 

    class Mammal < Animal 
     def initialize 
      @detail = { 
       :legs => 4 
       :babyfood => "Milk" 
       :special_ability => nil 
      } 
     end 
    end 

    class Cat < Animal 
     def initialize 
      @detail = { 
       :sharpclaws => "very Sharp" 
       :special_ability => "Climb a tree" 
      } 
     end 
    end 

    class Dog < Animal 
     def initialize 
      @detail = { 
       :best_friend => "Human" 
       :special_ability => "Bark" 
      } 
     end 
    end 
end 

但在IRB終端結果運行是

SyntaxError: ./learningruby.rb:25: syntax error, unexpected tSYMBEG, expecting '}' 
        :legs => 2 
        ^
./learningruby.rb:30: class definition in method body 
./learningruby.rb:34: syntax error, unexpected tSYMBEG, expecting '}' 
        :babyfood => "Milk" 
        ^
./learningruby.rb:35: syntax error, unexpected tASSOC, expecting kEND 
        :special_ability => nil 
            ^
./learningruby.rb:40: class definition in method body 
./learningruby.rb:44: syntax error, unexpected tSYMBEG, expecting '}' 
        :special_ability => "Climb a tree" 
        ^
./learningruby.rb:45: syntax error, unexpected '}', expecting kEND 
./learningruby.rb:49: class definition in method body 
./learningruby.rb:53: syntax error, unexpected tSYMBEG, expecting '}' 
        :special_ability => "Bark" 
        ^
./learningruby.rb:54: syntax error, unexpected '}', expecting kEND 
    from (irb):1:in `require' 
    from (irb):1 
    from :0 

對不起,如果我的問題這麼長時間,但感謝...

+2

您需要的哈希值之間的逗號:'翼:2,雙腿:2' –

回答

5

你缺少逗號:@detail = { :wing => 2, :legs => 2 }

+0

哦,謝謝你! –

0

你有兩個問題:

首先,你錯過了很多逗號:

@detail = { :wing => 2, :legs => 2 } 

@detail = { :legs => 4, :babyfood => "Milk", :special_ability => nil } 

@detail = { :sharpclaws => "very Sharp", :special_ability => "Climb a tree" } 

@detail = { :best_friend => "Human", :special_ability => "Bark" } 

其次,你的@detail哈希,則不能使用數組的join()方法。如果你想使它成爲一個字符串,試試這個:

@detail.map{|k,v| "#{k}=#{v}"}.join(',') 
=> "wing=2,legs=2" 
...