OOP is an interesting concept, one that many languages revolve around. During my introduction to JavaScript, OOP was a part of the course I hadn't touched. Needless to say, once I got into Ruby the concept was a little difficult to wrap my head around.
What is OOP?
(almost) Everything in ruby is an object, which is kind of a weird concept. Objects can hold state, react to other methods, and even have a unique identity. You can call .object_id on anything in ruby and get a unique number that is never repeated.
arr = [1, 2, 3, 4]
#=> [1, 2, 3, 4]
arr.object_id
#=> 360
arr.class
#=> Array
Above you can see the .class method as well, every ruby object belongs to a class, but what does that mean?
Classes & Instances
My instructor put it like this, Classes are like little factories responsible for managing and creating instances. We can define a class for anything, and create unique methods.to.chain.onto.it!
Here's a fun example:
class Dog
def greet
puts "Woof Woof!"
end
end
Bug = Dog.new
Bug.greet
#=> "Woof Woof!"
Bug.class
#=> Dog
Does this make sense? We defined a whole new class of objects called Dog, and were creating a special method for it! Think of it like .map() in JavaScript, we can only call the .map() method on an array and nothing else. While this example isn't quit as strict as that, the idea here is to create instances of dogs and a method to grab some information or interact with that dog object.
What does an instance look like?
Lets create an instance, but lets also give it a little more information. We can do this with instance variables.
class Dog
def name=(name)
# @name is an instance variable
@name = name
end
def name
@name
end
end
dog1 = Dog.create
dog1.name = "Bug"
dog1.name
#=> "Bug"
Now if we were to grab that instance we named Bug, it would look like this!
# .first is a built in class method that will grab the first
# instance of a class
Dog.first
#=> <Dog:0x000055ed811b7b90 id: 1, name: "Bug">
You can see that the Dog instance also was assigned a unique ID, this is useful for when we need to store multiple instances, with or without a name. These instances sort of resemble an array, or JavaScript object. We can even access data from them similarly to a JavaScript object.
Dog.first.name
#=> "Bug"
The Takeaway
I should become pretty clear how this structure could be useful. Instances could be users in a game, you could store them in a database, and have a separate table in that database be that users inventory. We can tie everyone together with ID's, receive a request from a client and build custom methods to interact with our data before sending back the response! The possibilities are pretty expansive, and reading Ruby is very easy compared to other languages. I cant wait to design my first little game in ruby!
Top comments (0)