如何避免类和全局变量

bin*_*son 5 ruby memory variables scope coding-style

Rubocop确认了《 Ruby样式指南》。它不鼓励使用实例变量之外的任何东西。我发现不至少使用类变量令人困惑。样式指南中的此代码片段不赞成使用全局变量,而是建议使用模块实例变量

# bad
$foo_bar = 1

# good
module Foo
  class << self
    attr_accessor :bar
  end
end

Foo.bar = 1
Run Code Online (Sandbox Code Playgroud)

谨慎使用全局变量是有道理的,但是既不使用全局变量也不使用类变量会让我大吃一惊。

模块实例变量类实例变量中,哪个更有效地使用内存?

例如:

选项A(类实例变量):

# things that exist only with life
module Life
  # an instance of life with unique actions/attributes
  class Person
    attr_accessor :memories

    def initialize
      @memories = []
    end

    def memorize(something)
      @memories << something
    end
  end
end

bob = Life::Person.new
bob.memorize 'birthday'
bob.memorize 'wedding'
bob.memorize 'anniversary'

bob.memories
# => ["birthday", "wedding", "anniversary"]
Run Code Online (Sandbox Code Playgroud)

选项B(模块实例变量):

# things that exist only with life
module Life
  # something all living things possess
  module Memory
    class << self
      attr_accessor :memories
    end
  end

  # an instance of life with unique actions/attributes
  class Person
    include Memory

    def initialize
      Memory.memories = []
    end

    def memorize(something)
      Memory.memories << something
    end

    def memories
      Memory.memories
    end
  end
end

bob = Life::Person.new
bob.memorize 'birthday'
bob.memorize 'wedding'
bob.memorize 'anniversary'

bob.memories
# => ["birthday", "wedding", "anniversary"]
Run Code Online (Sandbox Code Playgroud)

Ser*_*sev 3

您误解了术语“类实例变量”。它的意思是“Class对象上的实例变量”,而不是“某个类的实例上的实例变量”。

  class Person
    attr_accessor :memories # instance variable, not shared

    class << self
      attr_accessor :memories # class instance variable, shared between
                              # all instances of this class
    end
  end
Run Code Online (Sandbox Code Playgroud)

显然,有时您确实需要使用类实例变量。避免使用类变量 ( @@memories),因为它们在层次结构中的所有类(该类及其子类)之间共享,这可能会导致令人惊讶的行为。