From 80c71ef1c849d4294e13c3dbfce6fad66a79e99a Mon Sep 17 00:00:00 2001 From: greybird Date: Wed, 7 Aug 2013 11:20:20 +0400 Subject: Ruby. Difference between class instance variables and class variables --- ruby.html.markdown | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'ruby.html.markdown') diff --git a/ruby.html.markdown b/ruby.html.markdown index a3bcbbd5..99817982 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -325,4 +325,50 @@ dwight.name #=> "Dwight K. Schrute" # Call the class method Human.say("Hi") #=> "Hi" +# Class also is object in ruby. So class can have instance variables. +# Class variable is shared among the class and all of its descendants. + +# base class +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# derived class +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Class instance variable is not shared by the class's descendants. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + ``` -- cgit v1.2.3