0

我建立了一个妈妈是“动物”的班级并建立了一个孩子的班级。我从子类继承到母类,但我的代码有问题,我必须解决这个问题,但不好请帮助我,我是新手

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

对不起,如果我的问题这么长,但谢谢...

4

2 回答 2

5

您缺少逗号:@detail = { :wing => 2, :legs => 2 }

于 2012-11-15T12:47:05.823 回答
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"
...
于 2012-11-15T14:37:53.917 回答