类方法(红宝石) [英] Class methods (ruby)

查看:81
本文介绍了类方法(红宝石)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Newbie here, having a hard time understanding Class methods and why I cannot get an attribute to show up correctly in the instance.

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

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

When I use the class method create_with_attributes (on animal.2), I expect "white" to appear when I puts animal2.color.

好像我已经使用attr_accessor定义了它,就像我有噪点"一样,但是噪点正确显示,而颜色却没有.运行此程序时没有出现错误,但是.color属性没有出现.我相信是因为我在代码中以某种方式错误地标记了它.

It seems as though I have defined it using attr_accessor just like I have "noise", and yet noise appears correctly while color will not. I do not get an error when I run this program, but the .color attribute is just not appearing. I believe it is because I have somehow labeled it incorrectly in the code.

推荐答案

self.create_with_attributes是一种类方法,因此在其中设置@noise@color并不是设置实例变量的 ,而是称为类实例变量.

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.

您要执行的操作是在刚刚创建的实例上设置变量,因此,将self.create_with_attributes更改为类似以下内容:

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.

这篇关于类方法(红宝石)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆