红宝石/在多个类之间共享单个变量的能力 [英] ruby / ability to share a single variable between multiple classes

查看:49
本文介绍了红宝石/在多个类之间共享单个变量的能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一般类的操纵理解;给出以下用例:

For general classes manipulation understanding; given the following use case :

class Child1
  def process var
    'child1' + var
  end
end

class Child2
  def process var
    'child1' + var
  end
end

class Child3
  def process var
    'child3' + var
  end
end

...

class Master
  attr_reader :var
  def initialize(var)
    @var = var
  end

  def process
    [
      Child1.new.process(var),
      Child2.new.process(var),
      Child3.new.process(var)
    ]
  end
end

通过某种继承或结构,是否有办法让所有孩子都可以使用 var ?

by some kind of inheritance or structure, would there be a way to have var available to all children ?

含义:

class Child1 < Inherited
  def process
    'child1' + var
  end
end

...

class Master
  ...
  def process
    [
      Child1.new.process,
      ...
    ]
  end
end

我不太了解我所能找到的首选方法(尽管上面的第一个示例确实可以正常工作,虽然可能不是最优雅的方法);感谢您的指导

I don't know my thing enough to find the preferred approached (eventhough the first example above do work ok, while not being the most elegant probably); thanks for any guidance

推荐答案

我认为您正在寻找类变量.

I think you're looking for class variables.

类变量

Class 变量在类,其子类和它的实例.

Class Variables

Class variables are shared between a class, its subclasses and its instances.

类变量必须以 @@ (两个"at"符号)开头.名称的其余部分遵循与实例变量相同的规则.

A class variable must start with a @@ (two "at" signs). The rest of the name follows the same rules as instance variables.

这里是一个例子:

class A
  @@class_variable = 0

  def value
    @@class_variable
  end

  def update
    @@class_variable = @@class_variable + 1
  end
end

class B < A
  def update
    @@class_variable = @@class_variable + 2
  end
end

a = A.new
b = B.new

puts "A value: #{a.value}"
puts "B value: #{b.value}"

此打印:

A value: 0
B value: 0

继续同一示例,我们可以使用任一类中的对象进行更新,并且共享值:

Continuing with the same example, we can update using objects from either class and the value is shared:

puts "update A"
a.update

puts "A value: #{a.value}"
puts "B value: #{b.value}"

puts "update B"
b.update

puts "A value: #{a.value}"
puts "B value: #{b.value}"

puts "update A"
a.update

puts "A value: #{a.value}"
puts "B value: #{b.value}"

此打印:

update A
A value: 1
B value: 1
update B
A value: 3
B value: 3
update A
A value: 4
B value: 4

访问未初始化的类变量将引发 NameError 异常.

Accessing an uninitialized class variable will raise a NameError exception.

请注意,类具有实例变量,因为类是对象,所以请不要混淆类和实例变量.

Note that classes have instance variables because classes are objects, so try not to confuse class and instance variables.

这篇关于红宝石/在多个类之间共享单个变量的能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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