, p #what_am_i, , , BaseMod, OUTPUT . , Ruby OUTPUT, , , , Tall Short, . , , , , (. Tall.Ancestors). . :
module Personhood
def what_am_i; @output end
end
class Tall
include Personhood
def initialize
@output = "I am tall"
end
end
end
class Short
include Personhood
def initialize
@output = "I am short"
end
end
end
def Person( type )
if type =~ /short/i
Short.new
else
Tall.new
end
end
pete = Person "short"
pete.what_am_i
=> I am short
I chose a constant in favor of instance variables. There are no real constants in Ruby. Tall and Short are classes, and Person is a constructor method that returns the Tall or Short class depending on its input. This is how I feel it should be done.
source
share