我一直试图让这段代码输出:
'Mary has a pet called Satan.'
但我得到的是:
'Mary has a pet called #<Cat:0x00000002784c20>'
以下代码:
class Person
def initialize(name)
@name = name
@pet = nil
@hobbies = []
end
def describe()
puts "This persons name is #{@name}."
puts "#{@name}'s hobbies are:"
@hobbies.map { |hobby| puts hobby }
if @pet == nil
puts "#{@name} has not got any pets."
else
puts "#{@name} has a pet called #{@pet}"
end
end
attr_accessor :pet, :hobbies
end
class Cat < Animal
def initialize(name)
@name = name
end
end
satan = Cat.new("Satan")
mary = Person.new("Mary")
mary.pet = satan
mary.describe
感谢您的帮助。
答案 0 :(得分:2)
在describe()
函数中,您在不指定名称的情况下调用对象Cat
。
但如果你打电话给#{pet.name}
,它会抛出:
<undefined method `name' for #<Cat:0x0055d750a1a450 @name="Satan">
您必须先使用attr_accessor
name
课程中的变量Cat
class Cat < Animal
attr_accessor :name # First allow access
end
class Person
def describe()
puts "#{@name} has a pet called #{@pet.name}" # Then call the pet's name!
end
end