This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Class methods are used when a method needs to have functionality but it may not be tied to a specific instance of a class. The extend keyword in Ruby will mix behavior in to a class rather than instances of a class.
Code Samples
We've created a tracking module that creats an instances of something, pushes it on to an instances
array, and then can find it in said array.
module Tracking
def create(name)
object = new(name)
instances.push(object)
return object
end
def instances
@instances ||= []
end
def find(name)
instances.find do |instance|
instance.name == name
end
end
end
From there, when we use the extend
keyword, these methods will apply at the class level and not the instance level.
class Customer
extend Tracking
attr_accessor :name
def initialize(name)
@name = name
end
def to_s
"[#{@name}]"
end
end
Those methods now run at the class level and return instances of the class we just created:
puts "Customer.instances: %s" % Customer.instances.inspect
Output:
Customer.instances: []
Input:
puts "Customer.create: %s" % Customer.create("Jason")
Output:
Customer.create: [Jason]
Input:
puts "Customer.create: %s" % Customer.create("Kenneth")
Output:
Customer.create: [Kenneth]
Input:
puts "Customer.instances: %s" % Customer.instances.inspect
Output:
Customer.instances: [#<Customer:0x007f2b23eabc08 @name="Jason">, #<Customer:0x007f2b23eaba
f0 @name="Kenneth">]
Output:
puts "Customer.find('Jason'): %s" % Customer.find("Jason")
Output:
Customer.find('Jason'): [Jason]
Input:
puts "Customer.find('Mike'): %s" % Customer.find("Mike")
Output:
Customer.find('Mike'):
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up