Skip to content

Instantly share code, notes, and snippets.

def ticket.venue
"Town Hall"
end
def ticket.performer
"Mark Twain"
end
def ticket.event
"Author's reading"
end
def ticket.price
Macintosh:rubysamplecode toreystriffolino$ ruby ticket.rb
This ticket is for: ticket.rb:3:in `<main>': undefined method `event' for #<Object:0x007fcd6b04b678> (NoMethodError)
>> ticket = Object.new
=> #<Object:0x007fcc5a849c38>
>> def ticket.venue
>> "Town Hall"
>> end
=> nil
>> def ticket.performer
>> "Mark Twain"
>> end
=> nil
ticket = Object.new
print "This ticket is for: "
print ticket.event + ", at"
print ticket.venue + ", on "
puts ticket.date + "."
print "The performer is "
puts ticket.performer + "."
print "the seat is "
print ticket.seat + ", "
print "and it costs $"
NoMethodError: undefined method `talk' for #<Object:0x007ffcc9060a40>
from (irb):2
from /Users/toreystriffolino/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `<main>'
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
Macintosh:rubysamplecode toreystriffolino$ irb --simple-prompt
>> obj = Object.new
=> #<Object:0x007f98d8860998>
>>
LoadError: cannot load such file -- ./users/toreystriffolino/desktop/rubystuff/rubysamplecode/loadee
from /Users/toreystriffolino/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in `require'
from /Users/toreystriffolino/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in `require'
from (irb):3
from /Users/toreystriffolino/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `<main>'
total 64
-rw-r--r--@ 1 toreystriffolino staff 99 Oct 16 22:02 c2f.rb
-rw-r--r--@ 1 toreystriffolino staff 165 Oct 16 22:08 c2fi.rb
-rw-r--r--@ 1 toreystriffolino staff 202 Oct 16 23:28 c2fin.rb
-rw-r--r-- 1 toreystriffolino staff 208 Oct 19 12:54 c2fout.rb
-rw-r--r-- 1 toreystriffolino staff 105 Oct 19 12:48 loaddemo.rb
-rw-r--r-- 1 toreystriffolino staff 33 Oct 19 12:51 loadee.rb
-rw-r--r--@ 1 toreystriffolino staff 3 Oct 16 22:45 temp.dat
-rw-r--r-- 1 toreystriffolino staff 5 Oct 19 12:57 temp.out