mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 15:24:09 +03:00
Adds class documentation written by @joelwalden in #95
This commit is contained in:
parent
705e8fd023
commit
99192fea52
@ -251,4 +251,56 @@ surround { puts 'hello world' }
|
|||||||
# {
|
# {
|
||||||
# hello world
|
# 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. (Can only be called on class, not an instance).
|
||||||
|
|
||||||
|
def self.say(msg)
|
||||||
|
puts "#{msg}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def species
|
||||||
|
@@species
|
||||||
|
end
|
||||||
|
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
|
# Instantiate a class
|
||||||
|
jim = Human.new("Jim Halpert")
|
||||||
|
|
||||||
|
dwight = Human.new("Dwight K. Schrute")
|
||||||
|
|
||||||
|
# Let's call a couple of methods
|
||||||
|
jim.species #=> "H. sapiens"
|
||||||
|
jim.name #=> "Jim Halpert"
|
||||||
|
dwight.species #=> "H. sapiens"
|
||||||
|
dwight.name #=> "Dwight K. Schrute"
|
||||||
|
|
||||||
|
# Call the class method
|
||||||
|
Human.say("Hi") #=> "Hi"
|
||||||
```
|
```
|
Loading…
Reference in New Issue
Block a user