在 Ruby 中初始化类对象变量 [英] Initialize class object variable in Ruby

查看:42
本文介绍了在 Ruby 中初始化类对象变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我创建了一个类

class Result
    @@min = 0
    @@max = 0
    def initialize(min, max)
        @@max.min = min
        @@max.max = max
    end
end

result = Result.new(1, 10)
result.max

与其他语言相同.像 php、C# 等,我创建了一个类并传递了一个值,因为它有 initialize 方法,它现在应该包含对象值,但是当我尝试打印时

Same as other lang. like php, C# etc I have created a class and pass a value and since it has initialize method it will should now contains the object values but when I try to print out

puts result.min
puts result.max

它说未定义的方法 min

推荐答案

在 Ruby 中,@@ 在变量之前意味着它是一个类变量.您需要的是变量前的单个 @ 来创建实例变量.当您执行 Result.new(..) 时,您正在创建 Result 类的实例.

In Ruby, @@ before a variable means it's a class variable. What you need is the single @ before the variable to create an instance variable. When you do Result.new(..), you are creating an instance of the class Result.

您不需要像这样创建默认值:

You don't need to create default values like this:

@@min = 0
@@max = 0

你可以在initialize方法中进行

def initialize(min = 0, max = 0)

如果没有传入值,这会将 minmax 初始化为零.

This will initialize min and max to be zero if no values are passed in.

所以现在,您的 initialize 方法应该类似于

So now, your initialize method should like something like

def initialize(min=0, max=0)
    @min = min
    @max = max
end

现在,如果您希望能够在类的实例上调用 .min.max 方法,您需要创建这些方法(称为 setter 和吸气剂)

Now, if you want to be able to call .min or .max methods on the instance of the class, you need to create those methods (called setters and getters)

def min # getter method
  @min
end

def min=(val) # setter method
  @min = val
end

现在,您可以这样做:

result.min     #=> 1
result.min = 5 #=> 5

Ruby 有这些 setter 和 getter 的快捷方式:

Ruby has shortcuts for these setters and getters:

  • attr_accessor:创建 setter 和 getter 方法.
  • attr_reader:创建 getter 方法.
  • attr_writer:创建setter方法.
  • attr_accessor: creates the setter and getter methods.
  • attr_reader: create the getter method.
  • attr_writer: create the setter method.

要使用这些,您只需要执行 attr_accessor :min.这将为 min 创建两个方法,因此您可以直接通过实例对象调用和设置最小值.

To use those, you just need to do attr_accessor :min. This will create both methods for min, so you can call and set min values directly via the instance object.

现在,你的代码应该是这样的

Now, you code should look like this

class Result
    attr_accessor :min, :max
    def initialize(min=0, max=0)
        @min = min
        @max = max
    end
end

result = Result.new(1, 10)
result.max #=> 10

这篇关于在 Ruby 中初始化类对象变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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