Ivy's Blog about DBC

And how she survives it

CLASSES!!!

February 7th, 2016

So this week I did a lot of Class related work. Do I understand classes 100%? Nope.

In fact, I'll have to update this if I catch errors in my n00b mistakes later on.

So if you know about methods like...

def age(age)
p "My age is #{age}"
end

age(26)

Then you'll ask later on what if you want to make a BUNCH of methods related to a person but don't want it within one method. I mean, the methods could print name, age, and favorite food. Most of the time, people's names don't change over time (unless married/legal name change but different story...) but their age changes every year and their favorite food could change from day to day! This becomes tedious to fix per method. SO time for a class!

class person
#This will give us a new person. Initialize is to signal the start of a class.
def initialize(name)
p name
end
#This will give us the age
def age(year_born)
age = (2016) - year_born
end
#This will give us their favorite food
def favorite_food(food)
p favorite_food
end
end

#Here we are saying that jane is something to be passed through the class 'person'
jane = person.new("Jane")
jane.age(1979)
jane.favorite_food("Apple Pie")

And that's what I know so far. You could make what is called 'instance variables'. They look like @variable_name with a '@' in front of them. These are used so that the variable can be used in other methods. In general, if you have a variable defined in one method as just a regular variable like var_age = 23 , you can't use it in another method UNLESS you add the '@',@var_age = 23. Now you can use it in another method!