summaryrefslogtreecommitdiffhomepage
path: root/ruby.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'ruby.html.markdown')
-rw-r--r--ruby.html.markdown106
1 files changed, 76 insertions, 30 deletions
diff --git a/ruby.html.markdown b/ruby.html.markdown
index a3bcbbd5..861a94ad 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -275,36 +275,36 @@ surround { puts 'hello world' }
# Define a class with the class keyword
class Human
- # A class variable. It is shared by all instances of this class.
- @@species = "H. sapiens"
-
- # Basic initializer
- def initialize(name, age=0)
- # Assign the argument to the "name" instance variable for the instance
- @name = name
- # If no age given, we will fall back to the default in the arguments list.
- @age = age
- end
-
- # Basic setter method
- def name=(name)
- @name = name
- end
-
- # Basic getter method
- def name
- @name
- end
-
- # A class method uses self to distinguish from instance methods.
- # It can only be called on the class, not an instance.
- def self.say(msg)
- puts "#{msg}"
- end
-
- def species
- @@species
- end
+ # A class variable. It is shared by all instances of this class.
+ @@species = "H. sapiens"
+
+ # Basic initializer
+ def initialize(name, age=0)
+ # Assign the argument to the "name" instance variable for the instance
+ @name = name
+ # If no age given, we will fall back to the default in the arguments list.
+ @age = age
+ end
+
+ # Basic setter method
+ def name=(name)
+ @name = name
+ end
+
+ # Basic getter method
+ def name
+ @name
+ end
+
+ # A class method uses self to distinguish from instance methods.
+ # It can only be called on the class, not an instance.
+ def self.say(msg)
+ puts "#{msg}"
+ end
+
+ def species
+ @@species
+ end
end
@@ -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
+
```