Chapter 8: Interesting Objects

8.1 What's interesting?

8.2 Packages

8.3 Point objects

#!/usr/bin/env ruby

require "point"

blank = Point.new(3, 4)

8.4 Instance variables

#!/usr/bin/env ruby

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

#!/usr/bin/env ruby

require "point"

blank = Point.new(3, 4)

########################################

def print_point(point)
  puts "(#{point.x}, #{point.y})"
end

#print_point(blank)

########################################

puts blank

########################################

def distance(p1, p2)
  dx = p2.x - p1.x
  dy = p2.y - p1.y
  return Math.sqrt(dx*dx + dy*dy)
end

#puts distance(blank, Point.new)

8.6 Rectangles

#!/usr/bin/env ruby

require "rectangle"

box = Rectangle.new(0, 0, 100, 200)

########################################

puts box
# Rectangle[x=0, y=0, width=100, height=200]

8.7 Objects as return types

#!/usr/bin/env ruby

require "rectangle" # and rectangle imports point

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

#!/usr/bin/env ruby

require "rectangle"

box = Rectangle.new(0, 0, 100, 200)

########################################

box.x = box.x + 50
box.y = box.y + 100

#puts box

########################################

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

#Rectangle[x=50, y=100, width=100, height=200]

########################################

box.translate!(50, 100)

#puts box

8.9 Aliasing

#!/usr/bin/env ruby

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

#!/usr/bin/env ruby

require "point"

blank = nil

########################################

blank = nil
#x = blank.x              # NameError
#blank.translate!(50, 50) # NameError

########################################

#x = blank + 6 # NameError

=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

#!/usr/bin/env ruby

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

GNU Free Documentation License Valid HTML Valid CSS Built with BBEdit
Friendly links for Google “juice”