So I was doing a refresher on Ruby and I saw this guy's blog about creating class-level instance variable in Ruby. I am still trying to understand what the code actually does here. His blog can be found here
http://railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/
and I have created a simple code based on his example to show what I am 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 is (probably you guys have guessed it),
class << self; attr_accessor :sides end
What does this really do? what is he appending self to class ? is class an array then? Please elaborate as开发者_运维知识库 much as you can. Thank you.
The <<
is not a method (that is not exclusive to Array BTW), but is the syntax for defining a metaclass
Basically, a metaclass is THE class of a single object (some people calls them singleton classes). For example, if you define
x = Foo.new
y = Foo.new
class << x
def quack
"Quack!"
end
end
then calling x.quack
will return "Quack", but y.quack
will throw a NoMethodError
. So, the code is only evaluated on x's metaclass.
But... classes are objects too, right? So, when you evaluate that line, it is the equivalent of doing
class << Triangle
attr_accessor :sites
end
which will just define an instance variable in the metaclass of Triangle. This is, the Triange
class, which is an object too, will have an instance variable called sides
More info in this and this links. Once you get the idea, go to the nearest irb console and experiment with that.
精彩评论