Ruby Classes and College Basketball

Using Ruby classes to access information about starting lineups

Ruby is a great language for many reasons: easy syntax, it's object-oriented and you can accomplish a lot with just a little code. The most effective way of tying all of these aspects together is grouping data into classes.

What the heck is a class?

A class is a structure that binds data and functionality together, allowing you to easily create new objects that inherit data and functionality.

Let's look at this in a more comprehensive way. Let's say you wanted to quickly create a bracket for a basketball tournament that included the starting five players for each team.

Let's make one

Let's create our class

class BasketballTeam

end

Now we need to make it so that any new instance of BasketballTeam can take five players and make that data accessible. I'll expand on that in a minute.

class BasketballTeam
def initialize(pg, sg, sf, f, c)
@pg = pg
@sg = sg
@sf = sf
@f = f
@c = c
end
end

Now let's make it so that you can quickly access each player's name by position (i.e. Point guard for Michigan State. Which makes me a little sad. He would have been an All-American if hadn't hurt his wrist). We'll define methods point_guard, shooting_guard, small_forward, forward and center that, when called for a new instance of class BasketballTeam, will return the name of the player.

class BasketballTeam
def initialize(pg, sg, sf, f, c)
@pg = pg
@sg = sg
@sf = sf
@f = f
@c = c
end

def point_guard
puts "#{@pg}"
end

def shooting_guard
puts "#{@sg}"
end

def small_forward
puts "#{@sf}"
end

def forward
puts "#{@f}"
end

def center
puts "#{@c}"
end
end

Now let's create a few teams and grab individual players.

class BasketballTeam
def initialize(pg, sg, sf, f, c)
@pg = pg
@sg = sg
@sf = sf
@f = f
@c = c
end

def point_guard
puts "#{@pg}"
end

def shooting_guard
puts "#{@sg}"
end

def small_forward
puts "#{@sf}"
end

def forward
puts "#{@f}"
end

def center
puts "#{@c}"
end
end


MSU = BasketballTeam.new("Keith Appling", "Gary Harris", "Denzel Valentine", "Branden Dawson", "Adreian Payne")
MSU.center #-> Adreian Payne

UConn = BasketballTeam.new("Shabazz Napier", "Ryan Boatright", "Omar Calhoun", "DeAndre Daniels", "Tyler Olander")
UConn.small_forward #-> Omar Calhoun

UK = BasketballTeam.new("Andrew Harrison", "Aaron Harrison", "Alex Poythress", "Julius Randle", "Willie Cauley-Stein")
UK.point_guard #-> Andrew Harrison

This is a simple demonstration of how a class works, but the benefits are obvious: we are making our code much more DRY and allowing ourselves tons of flexibility to change and upgrade our class later on as our needs change.

Take me back >>