Tumgik
khan-kahani-blog · 5 years
Text
Classes in Ruby
What are Classes in Ruby?
The first time that you are introduced to Object Oriented Ruby, for some there is a slight disconnect what you are trying to accomplish and why.  You might struggle with understanding accessors, readers, writers, getters, setters, and the all important initialize.
I am going to try to simplify this process with something you might have seen before:
Tumblr media
When we initialize a new class we give it a Class Name.  Then we give it accessors (attributes).  
When an object is initialized it will either have attributes assigned to it or have a placeholder for those attributes ready to accept data from us.
Remember, we are working with a programming language in the terminal.  It does not have the ability to make a graphical spreadsheet.  
Our objects are the rows of our spreadsheet and and our accessors are our column headings.
Now let’s take this a step further.
Create a new class Song:
Tumblr media
What have we changed on our spreadsheet? 1) We have given it a name. (Ruby - defined a class) 2) We have given it attributes. (Ruby - attr_accessor :name, etc.) 3) We have given it some data. (Ruby - Song.new) 4) Each of our songs are also identified by a value in our first row.(Ruby -     object_id)  
Lets write this out in ruby:
class Song attr_accessor :artist, :album, :year_released, :song_name
@@all = [ ]
def initialize(artist, album, year_released, song_name)   @artist = artist   @album = album   @year_released = year_released   @song_name = song_name   @@all << self #This adds each instance of song we have created to our table end
def self.all   @@all end end
Song.new(“Artist 1”, “Album 1”, 2019, “Song1”) Song.new(“Artist 2”, “Album 2”, 2018, “Song2”) etc.
Take some time to compare your class to the spreadsheet above.  Next time, we will discuss the differences between class and instance methods.  Until then, I hope you have a greater understanding of Classes in Ruby.
1 note · View note