Classes Flashcards
About Ruby Classes
attr_acessor
- allows you to access variables inside and outside the class
- ruby is actually just adding a method behind the scenes in order for this to work.
class Spaceship attr_acessor :destination, :name
` def cancel_launch destination = “” # just a local variable self.destination = “” # variable that can be accessed because of attr_acessor endend`
Superclass and Subclass
- if you have something that’s very similar in functionality but gets really specialized then you can make a new class that inherits from the superclass.
- You can override methods in the superclass by making a method of the same name
add functionality to the superclass method that you are overriding
• You can add functionality to the superclass method that you are overriding just by adding the keyword “super”
EX
class Probe def deployment(deploy_time, return_time) puts "Deploying" endend
class MineralProbe < Probe def deploy(deploy_time) puts "Preparing sample chamber" super(deploy_time, Time.now * 2 * 60 * 60) endend
MineralProbe.new.deploy(Time.now)
Class methods and variables
class methods just have that self thing so you can call things on the class itself class variables aparently suck so don’t use them
class instance variables
classes defined outside methods in a class only to be used and returned in a method.
EX
class Spaceship @thruster_count = 2 def self.thruster_count @thruster_count endend
How to change characteristics/attributes defined in a superclass in its respective subclasses.
• define the superclass instance variable inside the subclasses
EX
class Spaceship @thruster_count = 2 def self.thruster_count @thruster_count endend
class SpritelySpaceship @thruster_count = 4end
class EconolingSpaceship @thruster_count = 1end
puts SpritelySpaceship.thruster_countputs EconolingSpaceship.thruster_countputs Spaceship.thruster_count412
Self
classes are just a context and self-refers to that context. So self. on a method in a class will refer to the class. But if you put a self. inside a method in the class, it will refer to the object that the method is being called on.
EX
class Spaceship def cancel_launch self.destination = "" seatbelt_sign(:off) endend
ship.cancel_launch# the self in cancel_launch refers to the ship object, and will therefore change its destination varaible.
Monkey Patching
Since classes are just a context for a workspace you can recall a class and just add to it creating new methods or overriding methods just by creating another method with the same name