ruby / ability to share a single variable between multiple classes

时间秒杀一切 提交于 2021-02-11 13:22:22

问题


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

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

Meaning :

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


回答1:


I think you're looking for class variables.

Class Variables

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

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

Here is an example:

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}"

This prints:

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}"

This prints:

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

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.



来源:https://stackoverflow.com/questions/52570749/ruby-ability-to-share-a-single-variable-between-multiple-classes

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