當我創建一個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 }
我建議清理問題的語言/內容,否則它會被刪除。 – xaxxon 2013-05-04 07:25:18