Skip to content

Instantly share code, notes, and snippets.

@randalmaile
Last active December 30, 2015 18:09
Show Gist options
  • Save randalmaile/7865550 to your computer and use it in GitHub Desktop.
Save randalmaile/7865550 to your computer and use it in GitHub Desktop.
Intro to Classes checkpoint
1. An instance of the Person class can do things like eat and sleep using instance methods, but it can also have attributes. For example, an instance of the Person class might have a name. The name of a person would therefore be an attribute of a Person instance.
2. Also, unlike local variables, instance variables start with a @. By making **@full_name an instance variable, we allow it to be used outside of the method where it's declared**. This is an important concept, and also known as a variable's scope. If we didn't make @full_name an instance variable, it would not be accessible outside of the method where it's declared!!!! HUGE!!! REPEAT THIS OVER AND OVER - GET IT INTO YOUR HEAD!!!!
3. Getter and setter methods are so common that Ruby provides a shortcut to create them. The attr_accessor method creates a getter and setter method based on an argument. You call the attr_accessor with a Symbol argument:
class Square
attr_accessor :size
end
s = Square.new
s.size = 10 # This is the setter
s.size #=> 10 # This is the getter
```Block output - basics
```
Book description should return title and author in description
```Block output - getters and setters
```
Book instance variables should be able get and set the title to 'LOTR'
Book instance variables should be able to set the title to 'Hitchhicker's Guide'
```Block output - attribute accessor
```
Playlist instance variables should be able to create a country playlist
Playlist instance variables should be able to create a Rock playlist
1. Are classes "Camel Case" or "Pascal Case"?
2. In Ruby - how do you distinguish between calling a property vs. a method?
# Basics
class Book
def title_and_author(title, author)
# set title to instance variable
# set author to instance variable
@title = title
@author = author
end
def description
# return a string with both instance variables
# "Title was written by author
"#{@title} was written by #{@author}"
end
end
#Getters and Setters
class Book
#setters
def title=(t)
@title = t
end
def author=(a)
@author = a
end
def pages=(p)
@pages = p
end
#getters
def title
@title
end
def author
@author
end
def pages
@pages
end
end
# Attr Accessor
class Playlist
attr_accessor :name
attr_accessor :author
attr_accessor :song_list
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment