类方法(红宝石)

时间:2012-04-28 18:57:46

标签: ruby instance-variables class-method

新手在这里,很难理解类方法以及为什么我无法在实例中正确显示属性。

class Animal
  attr_accessor :noise, :color, :legs, :arms

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

  def initialize(noise, legs=4, arms=0)
    @noise = noise
    @legs = legs
    @arms = arms
    puts "----A new animal has been instantiated.----"
  end
end

animal1 = Animal.new("Moo!", 4, 0)
puts animal1.noise
animal1.color = "black"
puts animal1.color
puts animal1.legs
puts animal1.arms
puts

animal2 = Animal.create_with_attributes("Quack", "white")
puts animal2.noise
puts animal2.color

当我使用类方法create_with_attributes(在animal.2上)时,我希望"white"出现puts animal2.color

似乎我使用attr_accessor定义它就像我有“噪音”一样,然而噪音正确显示而颜色则不然。运行此程序时,我没有收到错误,但.color属性没有出现。我相信这是因为我在代码中以某种方式错误地标记了它。

2 个答案:

答案 0 :(得分:3)

self.create_with_attributes是一种类方法,因此在其中设置@noise@color not 设置实例变量,而不是所谓的{{ 3}}

您要做的是在您刚刚创建的实例上设置变量,因此请将self.create_with_attributes更改为:

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

将在新实例上设置属性,而不是在类本身上设置属性。

答案 1 :(得分:1)

当您使用create_with_attributes方法时,实例变量会在Animal类本身上设置,而不是在您刚创建的Animal实例上设置。这是因为该方法位于Animal类(Class的实例)上,因此它在该上下文中运行,而不是Animal的任何实例的上下文。如果你这样做:

Animal.instance_variable_get(:@color)

运行您描述的方法后,您应该返回"white"

那就是说,你需要通过调用setter方法来设置你刚创建的实例的属性,如下所示:

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

我删除了noise的设置,因为无论如何,我已完成initialize