32
loading...
This website collects cookies to deliver better user experience
class CoolestCanadianActors # this class represents the coolest Canadian actors
def initialize(first, last) # The initialize method is part of the object-creation process in Ruby & it allows you to set the initial values for an object.
@first = first
@last = last
end
end
obj1 = Name.new("Ryan", "Reynolds") # we've created a new object with the name "Ryan Reynolds".
print obj1 # prints out object
initialize
method we were able to use the power of abstraction and create a new "cool Canadian actor". array = Array.new
array = []
hash = {}
string = ""
coolestCanadianCelebrity
class set up what is next? Well we can add behavior to our objects. We've already done this above with our initialize
method but lets dive a little deeper. def one_plus_one
1 + 1
end
coolestCanadianCelebrity.one_plus_one
coolestCanadianCelebrity
, NOT on coolestCanadianCelebrity
itself.class CoolestCanadianActors
def initialize(first, last)
@first = first
@last = last
end
end
obj1 = Name.new("Ryan", "Reynolds")
initialize
method is ran when you create a Ruby object. Within this method you will notice the first
, last
variables look slightly different from the variables we are used to working with. @first = first
@last = last
CoolestCanadianActors
object is created we want it to know how many twitter followers it has. How can I store the number of followers in the CoolestCanadianActors
class?class CoolestCanadianActors
def initialize(first, last)
@first = first
@last = last
@twitter_followers = twitter_followers
end
end
obj1 = Name.new("Ryan", "Reynolds", "17.7M")
obj1
. class CoolestCanadianActors
def initialize(first, last)
@first = first
@last = last
@twitter_followers = twitter_followers
end
end
obj1 = Name.new("Ryan", "Reynolds", "17.7M")
class CoolestCanadianActors
def initialize(first, last)
@first = first
@last = last
@twitter_followers = twitter_followers
end
def twitter_followers # getter method
@twitter_followers
end
end
obj1 = Name.new("Ryan", "Reynolds", "17.7M")
class CoolestCanadianActors
attr_accessor first, last, twitter_followers
def initialize(first, last, twitter_followers)
@first = first
@last = last
@twitter_followers = twitter_followers
end
end
class CoolestCanadianActors
attr_accessor :first, :last, :twitter_followers
def initialize(first, last, twitter_followers)
@first = first
@last = last
@twitter_followers = twitter_followers
end
end
twitter_followers
attribute? In others words, the data will be public and accessible to the user. attr_reader :twitter_followers
object
. The attr_reader
takes care of the getter's function which is to get a value of an instance variable.