Skip to content

Instantly share code, notes, and snippets.

@randalmaile
Last active December 30, 2015 18:18
Show Gist options
  • Save randalmaile/7866268 to your computer and use it in GitHub Desktop.
Save randalmaile/7866268 to your computer and use it in GitHub Desktop.
Intro to Classes 2 checkpoint
1. Getter and setter methods can be used for accessing the attributes of a class, but you'll often want to create a new instance of a class with default attribute values. **Getter and setter methods can only access attributes after an instance of a class has been created**. THIS IS HUGE!! REPEAT REPEAT REPEAT!!! Ruby has a standard method named initialize that is executed when you create a new class instance:
```code
class President
attr_accessor :age
def initialize(years)
@age = years
end
end
```
Now we are essentially creating an **interface** for our President class. We have allowed the age attribute to be set by a theoretical user, rather than "hard-coding" the value as we did in the prior example.
``` Block output - initialize
```
Car initialize should take make, model and year
``` Block output - class methods
```
Car initialize should take make, model and year
Car wheels should return a standard number of wheels for any car
Car axels should return a standard number of axels for any car
1. What exactly is an interface? This idea of creating a "prepackaged" class that's in a valid state reminds me of C# - when you write a "constructor." I'm probably confusing things. This is imp stuff - let's discuss :)
# INITIALIZE
class Car
attr_accessor :make
attr_accessor :model
attr_accessor :year
def initialize(make, model, year)
@make, @model, @year = make, model, year
end
end
# Class methods
class Car
attr_accessor :make
attr_accessor :model
attr_accessor :year
def initialize(make, model, year)
@make, @model,@year = make, model, year
end
def self.wheels
4
end
def self.axels
2
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment