Guest User

Untitled

a guest
Nov 18th, 2017
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #### Constants
  2. 1. Class constant - a variable at the class level so every object of that class can use it.
  3. `SHELL_COLOR = "Red"`
  4. 2. Class method - can only be called on the class
  5. ```ruby
  6. @@number_of_koopas = 0
  7.  
  8. def initialize(name)
  9. @name = name
  10. @@number_of_koopas += 1
  11. end
  12.  
  13. # method to expose the constant
  14. def shell_color
  15. SHELL_COLOR
  16. end
  17.  
  18. # class method
  19. def self.count
  20. @@number_of_koopas
  21. end
  22. ```
  23.  
  24. #### Self
  25. 1. refers to the thing the method was called on. To define a class method, add `self.` to the method name.
  26. 2. __implicit receiver__ - omitting self when referencing an instance variable inside an instance method.
  27.  
  28. #### Inheritence
  29. 1. Classical v. Prototypal - based on either, what the class is v. what the class does, respectively
  30. 2.
  31. ```ruby
  32. class Childclass < Parentclass
  33. end
  34. ```
  35. 3. Childclass.superclass - returns name of parent class
  36. 4. is_a? - accepts one param, returns true if object is member of param class
  37. 5. Polymorphism - we call a method of the parent class without concern for what child class we dealing with
  38. (but the child class by definition has access/contains the method inherited from parent class)
  39.  
  40. #### Modules
  41. 1. Encapsulate behavior that our classes can extend
  42. 2. Define behavior in a module that our classes can use without tying that behavior to a class.
  43. 3. Abstract behavior into it's own thing
  44. 4. Implement - a class 'implements' a module if it includes it
  45. ```ruby
  46. module Inventory
  47. def add_to_inventory(item)
  48. @inventory << item
  49. end
  50.  
  51. def remove_from_inventory(item)
  52. @inventory.delete(item)
  53. end
  54. end
  55.  
  56. class Player
  57. include Inventory # makes module available to the class
  58. attr_accessor :name, :inventory
  59.  
  60. def initialize(name)
  61. @name, @inventory = name, []
  62. end
  63.  
  64. end
  65.  
  66. class Chest
  67. include Inventory
  68.  
  69. attr_accessor :inventory
  70.  
  71. def initialize(inventory)
  72. @inventory = inventory
  73. end
  74. end
  75. ```
Add Comment
Please, Sign In to add comment