Monday, September 22, 2008

Duck Typing and Type Checking

Consider the following example:

class A
attr_accessor :x

def initialize
@x = 0
end

def +(other)
a = A.new
a.x = @x + other.x
return a
end
end

class B
attr_accessor :x

def initialize
@x = 0
end
end

a = A.new
a.x = 10
b = B.new
b.x = 5
puts (a+b).x # this will return 15

Ruby is a very dynamic language, the addition function doesn't care if the argument passed in is of type A, as long as it looks and behaves like A. This is called duck typing, name after the phase "if it walks like a duck and quacks like a duck, it must be a duck!"

if you want to ensure the object passed into the + function has to have an x accessor, you can add this to def +(other)

raise "error" unless other.respond_to? :x

or if you want to ensure object passed into the + function has to be of class A, you can add this instead:

raise "error" unless other.is_a? A


J

No comments: