ruby-talk
11/17/2007 1:40:00 PM
On Sat, Nov 17, 2007 at 03:32:03PM +0900, Thufir wrote:
> On Sat, 17 Nov 2007 14:36:50 +0900, Raul Parolari wrote:
>
> Fair enough. This is pretty much how Java would do it, and, correct me
> if I'm wrong, Smalltalk would probably do similarly.
>
> Put another way: there must be a non-contrived case of composition in
> Ruby? Yes?
>
What are you looking for? Composition is basically accomplished by
instance variables, even for less contrived cases. As for the
interface, to say TMTOWTDI is an understatement.
require 'forwardable'
class Engine
def vroom
puts "vroom"
end
end
class MustangEngine
def vroom
puts "rumble"
end
end
class Vehicle
extend Forwardable
def_delegator :@engine, :vroom
attr_accessor :engine
def initialize(engine)
@engine=engine
end
end
v=Vehicle.new(Engine.new)
v.vroom
v.engine=MustangEngine.new
v.vroom
As far as comparison to Java, this example uses duck typing. As long as it vrooms, you can use it as an engine for your vehicle.