Invert an instance of a Ruby class class

So, I was updating Ruby, and I saw this guy's blog about creating a class instance variable in Ruby. I'm still trying to figure out what the code is doing here. His blog can be found here.

http://railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/

and I created simple code based on his example to show what I'm trying to understand

class Polygon
  class << self; attr_accessor :sides end
  @sides = 10
  def initialize
  end
end

class Triangle < Polygon
  @sides = 3
  class << self; attr_accessor :sides end
  def initialize
  end
end

puts Triangle.sides #3
puts Polygon.sides #10

So the line that I really want to understand (maybe you guys guessed it)

class << self; attr_accessor :sides end

What does this really do? what does he add to the class? is an array an array? Please consider as much as possible. Thank.

+3
source share
1 answer

<< ( Array BTW), metaclass

, ( ). ,

x = Foo.new
y = Foo.new
class << x
  def quack
    "Quack!"
  end
end

x.quack "Quack", y.quack NoMethodError. , x .

... , ? , ,

class << Triangle
  attr_accessor :sites
end

. , Triange, , sides

this . , irb .

+6

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


All Articles