当我创建一个 Stats 类和另一个容器类时出现错误。错误是
test.rb:43:in `<main>' undefined method `each' for #<Boyfriends:0x2803db8 @boyfriends=[, , , ]> (NoMethodError)
这是绝对有意义的,因为该类确实不包含该方法,但是 ruby 是否应该在父类和祖父母类中搜索该方法?该脚本显示所需的输出;它只是像这样在输出中嵌入错误
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 }