Skip to content

Instantly share code, notes, and snippets.

@ToreySound
Created October 23, 2013 23:07
Show Gist options
  • Save ToreySound/7128447 to your computer and use it in GitHub Desktop.
Save ToreySound/7128447 to your computer and use it in GitHub Desktop.
Seeing a language-specific explanation of OOP can make the abstract parts easier to grasp. We’ll therefore proceed to some Ruby code. We’ll create a new object. It won’t represent or model anything specific, like a house or a book or a teacher; it will be a generic object:
obj = Object.new
Now you have an object and a variable through which you can address it.
DEFINING AN OBJECT’S BEHAVIOR
Let’s say you’ve created an object and you want it to do something interesting: you want it to talk. To get it to talk, you have to ask it to talk. But before you ask it to talk, you have to teach it how to talk.
Specifically, and more technically, you have to define a method for your object. You do this using a special term—a keyword—namely, the keyword def.
Here’s how to define the method talk for the object obj:
def obj.talk
puts "I am an object." puts "(Do you object?)"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment