Objective |
---|
To be able to create simple classes and methods |
Prev Work:
- Common Datatypes
- Loops, Conditionals
- Arrays, Hashes
- functions
Let's talk about
- Instance Variables (attributes)
- Class Variables
- Instance Methods or Object Methods
- Getter Methods
- Setter Methods
- attr_accessor, attr_reader, attr_writer
- self
greet_pc.rb
# takes two arguments:
# name and greeting
# greet(name, greeting) => "#{greeting} #{name}"
greet.rb
def greet(name, greeting)
puts "#{greeting} #{name}"
end
greets_pc.rb
# Create a method that takes a list of people
# and greets them their greetings
# greets(people, greetings)
greets.rb
people = [Kyle, Del, Jackie]
greetings = ["Hey", "Howdy", "Hi"]
def greets(people, greetings)
for x in (0..people.length - 1)
puts "#{greetings[x] #{people[x]}"
end
end
greets(people,greetings)
What happens when we want to start adding people? Then we have to go and also update their 'greeting'.
We could try to make this easier with something called a class
person_class.rb
class Person
def inititalize(name)
@name_attribute = name
end
def say_hello
"Hello, my name is #{@name_attribute}!"
end
end
person = Person.new("Jack")
person.say_hello # => "Hello my name is some_name"
What's going on here?
-
def initialize(..)
- creates a new object with the
.new(..)
method person = Person.new
creates an instance of aPerson
class and assigns it toperson
.
- creates a new object with the
-
@name_attribute
- the @name_attribute is an instance variable accessible by all the methods in the the object. We say @name_attribute is an 'attribute' of an object.
-
say_hello
- This is a function definition inside the object and is conventionally
called a Method.
- Note: The terms method and function may have been used interchangably before, but method should be used to mean an object's function
- This is a function definition inside the object and is conventionally
called a Method.
Lets Try another example
greeter.rb
class Greeter
def initialize(people)
@people = people
end
def greets
@people.each do |person, greeting|
puts "#{greeting} #{person}"
end
end
end
people = { "Kyle" => "Hey",
"Del" => "Howdie",
"Jackie" => "Hi"}
greeter = Greeter.new(people)
greeter.greets
A gets method
Person_2.rb
class Person
def initialize(name)
@name = name
end
def name
@name
end
end
greeter = Greeter.new
greeter.name
A set method
Person_3.rb
class Person
def initialize(name)
@name = name
end
def name
@name
end
def name=(other)
@name = name
end
end
person = Person.new("john")
puts person.name
person.name = "mike"
puts person.name
Adding a class Variables
people_4.rb
class Person
@@num_of_people = 0
def initialize(name)
@name = name
@@num_of_people += 1
puts @@num_of_people
end
def name
@name
end
def name=(other)
@name = other
end
end