So what is a class?
As we have been progressing through Ruby, we have learned many things. We have learned how methods work, and how we can manipulate them to do what we want. But what if we have multiple methods we want to use, for specific data, that we want to reuse?
Thats when we use a class.
There are many many examples of when to use a class. It may be difficult when to decide wether or not to use a class. The best advice to give, is to determine the desired input and output, then analyze how many methods will be required to accomplish your objective, and consider if you will need to repeat this code again at some point. A scenario where a class may be applicable is processing auction information.
Establishing a class
To establish a class you have to type "class" and the name you want to call your class. You also close your class with an end.
class AuctionArt
----------
end
Lets pretend we had an array of information about an auction, that had each artists name, the number of times someone bid on their work, and the price of the final bid. Now we can initialize some variable. Initialize is a constructor of class. Variables with @ are instance variables, and can be used within the scope of this class.
class AuctionArt
--def initialize(artist_name, num_of_art, num_of_bids, highest_bid)
----@artist_name = artist_name
----@num_of_art = num_of_art
----@num_of_bids = num_of_bids
----@highest_bid = highest_bid
--end
--def most_popular
----method using @most_bids and @highest_bid to determine a score of popularity.
--end
end
How to access this class?
monet = AuctionArt.new("Monet", 8, 42, 2900000)
monet.most_popular
matisse = AuctionArt.new("Matisse", 12, 83, 3450000)
matisse.most_popular
Obviously,
this code is just some pseudocode to give you an idea of how information is processed. Classes are really great for accepting different types of data including arrays and hashes, but also for looping and accepting and processing user input/information. For AuctionArt, we set the variable monet equal to AuctionArt.new with the array of information we wanted(we could have used hashes for more clarity), then took that new variable monet and passed it through the class method .most_popular. Lets say that the method .most_popular returns a score of 1 to 10, rating the popularity of the artist at the auction.
How did they rate?
monet = AuctionArt.new("Monet", 8, 42, 2900000)
monet.most_popular #==> 9
matisse = AuctionArt.new("Matisse", 12, 83, 3450000)
matisse.most_popular #==> 7
Monet returned a value of 9 and Matisse returned a value of 7 in popularity. Hope that helped a little bit with classes.
July 6, 2014