What does it mean that `attr_accessor` /` attr_reader` creates an instance variable?

The documentation for attr_accessorexplicitly states that it creates an instance variable:

[...] creating an instance variable ( @name) and the corresponding access method [...]

Like the documentation for attr_reader:

Creates instance variables and associated methods [...]

I understand the second part, i.e. that the methods attr_accessorand attr_readercreate, but I do not get the first part.

What does it mean that they "create an instance variable"?

+4
source share
2 answers

/ . attr_reader/attr_accessor . ? . . .

class Foo
  attr_accessor :bar
end

foo = Foo.new
foo.instance_variables # => []
foo.bar # try read ivar
foo.instance_variables # => [], nope, not yet
foo.bar = 2 # write ivar
foo.instance_variables # => [:@bar], there it is
+4

attr_accessor , :

[...] (@name) [...]

attr_reader:

[...]

, .. attr_accessor attr_reader , .

, " "?

, , , . , . Ruby (, C YARV, Java JRuby) , Ruby:

class Module
  def attr_reader(*attrs)
    attrs.each do |attr|
      define_method(attr) do
        instance_variable_get(:"@{attr}")
      end
    end
  end

  def attr_writer(*attrs)
    attrs.each do |attr|
      define_method(:"{attr}=") do |val|
        instance_variable_set(:"@{attr}", val)
      end
    end
  end

  def attr_accessor(*attrs)
    attr_reader(*attrs)
    attr_writer(*attrs)
  end
end
+2

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


All Articles