Class methods (ruby)

北城以北 提交于 2019-12-06 19:38:27

self.create_with_attributes is a class method, so setting @noise and @color within it is not setting an instance variable, but instead what's known as a class instance variable.

What you want to do is set the variables on the instance you've just created, so instead, change self.create_with_attributes to look something like:

 def self.create_with_attributes(noise, color)
     animal = self.new(noise)
     animal.noise = noise
     animal.color = color
     animal
 end

which will set the attributes on your new instance, instead of on the class itself.

When you're in the create_with_attributes method, the instance variables are set on the Animal class itself, not on the instance of Animal you've just created. This is because the method is on the Animal class (which is an instance of Class), and thus it is run within that context, not the context of any instance of Animal. If you do:

Animal.instance_variable_get(:@color)

after running the method like you describe, you should get "white" back.

That said, you need to instead set the attributes on the instance you've just created by calling the setter methods like so:

def self.create_with_attributes(noise, color)
  animal = self.new(noise)
  animal.color = color
  return animal
end

I removed the setting of noise since it's done in your initialize anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!