Chapter 8: Interesting Objects
8.1 What's interesting?
8.2 Packages
8.3 Point objects
require "point"
blank = Point.new(3, 4)
8.4 Instance variables
require "point"
blank = Point.new(3, 4)
x = blank.x
puts "#{blank.x}, #{blank.y}"
distance = blank.x * blank.x + blank.y * blank.y
8.5 Objects as parameters
require "point"
blank = Point.new(3, 4)
def print_point(point)
puts "(#{point.x}, #{point.y})"
end
puts blank
def distance(p1, p2)
dx = p2.x - p1.x
dy = p2.y - p1.y
return Math.sqrt(dx*dx + dy*dy)
end
8.6 Rectangles
require "rectangle"
box = Rectangle.new(0, 0, 100, 200)
puts box
8.7 Objects as return types
require "rectangle"
def find_center(box)
x = box.x + box.width/2.0
y = box.y + box.height/2.0
return Point.new(x, y)
end
box = Rectangle.new(0, 0, 100, 200)
puts find_center(box)
8.8 Objects are mutable
require "rectangle"
box = Rectangle.new(0, 0, 100, 200)
box.x = box.x + 50
box.y = box.y + 100
def move_rect(box, dx, dy)
box.x += dx
box.y += dy
end
box = Rectangle.new(0, 0, 100, 200)
move_rect(box, 50, 100)
puts box
box.translate!(50, 100)
8.9 Aliasing
require "rectangle"
box1 = Rectangle.new(0, 0, 100, 200)
box2 = box1
p box1, box2
puts box2
box1.grow!(50, 50)
puts box2
8.10 null
require "point"
blank = nil
blank = nil
=begin
But setting something to nil in Ruby is not the same as setting something to null in Java!!! I need to rethink this.
=end
8.11 Garbage collection
require "point"
blank = Point.new(3, 4)
blank = nil
p1 = Point.new(5, 7)
p1 = "hello"
=begin
But setting something to nil in Ruby is not the same as setting something to null in Java!!! I need to rethink this.
=end
8.12 Objects and primitives
8.13 Glossary
8.14 Exercises
Friendly
links for Google “juice”