Avoiding class and global variables

Rubocop endorses the Ruby Style Guide . He does not recommend using anything other than instance variables. I believe that confusing should not be used with the smallest class variables. This snippet from the style guide frowns regarding the use of global variables and instead recommends module instance variables:

# bad
$foo_bar = 1

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

Foo.bar = 1

It makes sense to be wary of using global variables, but using neither global variables nor class variables makes me crazy.

Among module instance variables and class instance variables, which uses memory more efficiently?

For example:

Option A (class instance variable):

# 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"]

Option B (module instance variable):

# 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"]
+4
1

" ". " 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), ( ), .

+3

Source: https://habr.com/ru/post/1609455/


All Articles