Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #### Constants
- 1. Class constant - a variable at the class level so every object of that class can use it.
- `SHELL_COLOR = "Red"`
- 2. Class method - can only be called on the class
- ```ruby
- @@number_of_koopas = 0
- def initialize(name)
- @name = name
- @@number_of_koopas += 1
- end
- # method to expose the constant
- def shell_color
- SHELL_COLOR
- end
- # class method
- def self.count
- @@number_of_koopas
- end
- ```
- #### Self
- 1. refers to the thing the method was called on. To define a class method, add `self.` to the method name.
- 2. __implicit receiver__ - omitting self when referencing an instance variable inside an instance method.
- #### Inheritence
- 1. Classical v. Prototypal - based on either, what the class is v. what the class does, respectively
- 2.
- ```ruby
- class Childclass < Parentclass
- end
- ```
- 3. Childclass.superclass - returns name of parent class
- 4. is_a? - accepts one param, returns true if object is member of param class
- 5. Polymorphism - we call a method of the parent class without concern for what child class we dealing with
- (but the child class by definition has access/contains the method inherited from parent class)
- #### Modules
- 1. Encapsulate behavior that our classes can extend
- 2. Define behavior in a module that our classes can use without tying that behavior to a class.
- 3. Abstract behavior into it's own thing
- 4. Implement - a class 'implements' a module if it includes it
- ```ruby
- module Inventory
- def add_to_inventory(item)
- @inventory << item
- end
- def remove_from_inventory(item)
- @inventory.delete(item)
- end
- end
- class Player
- include Inventory # makes module available to the class
- attr_accessor :name, :inventory
- def initialize(name)
- @name, @inventory = name, []
- end
- end
- class Chest
- include Inventory
- attr_accessor :inventory
- def initialize(inventory)
- @inventory = inventory
- end
- end
- ```
Add Comment
Please, Sign In to add comment