2013-05-04 42 views
-7

當我創建一個Stats類和另一個容器類時,出現錯誤。該錯誤是Ruby未定義方法'each'for class

test.rb:43:in `<main>' undefined method `each' for #<Boyfriends:0x2803db8 @boyfriends=[, , , ]> (NoMethodError) 

這使得絕對意義上的,因爲這確實類不包含該方法,而應紅寶石搜索父母和祖父母類的方法?該腳本顯示所需的輸出;它只是內嵌錯誤,象這樣

test.rb:43:in `<main>'I love Rikuo because he is 8 years old and has a 13 inch nose 
I love dolar because he is 12 years old and has a 18 inch nose 
I love ghot because he is 53 years old and has a 0 inch nose 
I love GRATS because he is unknown years old and has a 9999 inch nose 
: undefined method `each' for #<Boyfriends:0x2803db8 @boyfriends=[, , , ]> (NoMethodError) 

這裏輸出的代碼

class Boyfriends 
    def initialize 
     @boyfriends = Array.new 
    end 

    def append(aBoyfriend) 
     @boyfriends.push(aBoyfriend) 
     self 
    end 

    def deleteFirst 
     @boyfriends.shift 
    end 

    def deleteLast 
     @boyfriends.pop 
    end 

    def [](key) 
     return @boyfriends[key] if key.kind_of?(Integer) 
     return @boyfriends.find { |aBoyfriend| aBoyfriend.name } 
    end 
end 

class BoyfriendStats 
    def initialize(name, age, nose_size) 
     @name = name 
     @age = age 
     @nose_size = nose_size 
    end 

    def to_s 
     puts "I love #{@name} because he is #{@age} years old and has a #{@nose_size} inch nose" 
    end 

    attr_reader :name, :age, :nose_size 
    attr_writer :name, :age, :nose_size 
end 

list = Boyfriends.new 
list.append(BoyfriendStats.new("Rikuo", 8, 13)).append(BoyfriendStats.new("dolar", 12, 18)).append(BoyfriendStats.new("ghot", 53, 0)).append(BoyfriendStats.new("GRATS", "unknown", 9999)) 

list.each { |boyfriend| boyfriend.to_s } 
+3

我建議清理問題的語言/內容,否則它會被刪除。 – xaxxon 2013-05-04 07:25:18

回答

1

這使得絕對意義上的,因爲那類確實不包含這種方法,但我一直在閱讀應該紅寶石尋找類父母和祖父母的方法?

這是正確的,但你沒有聲明任何超這樣的超將是Object。其中也沒有each方法。

如果你想要一個可枚舉的方法,你必須自己定義它 - 你可能會想遍歷數組。

在這種情況下,你可以只定義一個自己的,只是通過傳遞塊下降到陣列each的方法,每個方法:

class Boyfriends 
    def each(&block) 
    @boyfriends.each(&block) 
    end 
end 

這裏的&block讓你的名字捕捉的一個傳遞塊。如果你對ruby不熟悉,這對你來說可能並不重要,並且解釋它的工作方式有點超出了這個問題的範圍。在this Question中接受的答案在解釋塊和yield的工作方式方面做得很好。

一旦你得到了一個每一個方法,你也可以拉Enumerable了許多的方便的方法:

class Boyfriends 
    include Enumerable 
end 

此外,to_s是應該返回一個字符串,所以你應該刪除在puts的方法BoyfriendStats#to_s

+0

謝謝你。我知道這是一個簡單的解決方案,但是因爲我剛剛開始使用紅寶石,所以我無法弄清楚。我將你的帖子標記爲答案,但我有一個問題。 '&'前綴在Ruby中對變量做了什麼?我不認爲我已經閱讀過關於它的任何內容。 – 2013-05-04 07:37:37

+0

儘管如此,我想知道輸出來自哪裏,在原始示例中。這是問題中有趣的部分。 – xaxxon 2013-05-04 07:39:30

+0

@xaxxon我在最後回答。他在他的'BoyfriendStats#to_s'方法中放了一個'puts',當Ruby嘗試顯示'Boyfriends'實例時導致輸出。 – Cubic 2013-05-04 07:44:53

相關問題