加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:24:57 所属栏目:百科 来源:网络整理
导读:Rubocop确认到 The Ruby Style Guide.它不鼓励使用除实例变量之外的任何内容.我发现不使用至少类变量会让人感到困惑.样式指南中的这个片段对全局变量的使用不以为然,而是推荐模块实例变量: # bad$foo_bar = 1# goodmodule Foo class self attr_accessor :ba
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","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),因为它们在层次结构中的所有类(类及其子代)之间共享,这可能会导致令人惊讶的行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读