ruby - 如何避免类和全局变量

标签 ruby variables memory scope coding-style

Rubocop确认 The Ruby Style Guide .它不鼓励使用实例变量以外的任何东西。我发现至少不使用类变量会让人感到困惑。风格指南中的这段代码对全局变量的使用表示不满,而是推荐使用模块实例变量:

# bad
$foo_bar = 1

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

Foo.bar = 1

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

模块实例变量类实例变量,哪个内存使用效率更高?

例如:

选项 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"]

选项 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"]

最佳答案

您误解了术语“类实例变量”。它的意思是“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

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

关于ruby - 如何避免类和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32841984/

相关文章:

循环内的 Java 变量

c - 重用变量是好是坏?

ruby - 如何使用Chewy更新Elasticsearch字段类型

ruby - 事件记录查询

java - java中的float和float有什么区别?

c - 在内存中查找进程页面(linux-kernel)

memory - 处理器是否使用Intel QuickPath Interconnect(QPI)来访问内存?

ruby - 匹配捕获组中前面或后面的字母字符的正则表达式

sql - 如何在 postgresql 和 rails 3 中按月分组

c++ - 将大型成员对象移出类?