From: Rick DeNatale Date: 2009-11-15T01:39:00+09:00 Subject: Re: Surprising behavior when extending instances On Sat, Nov 14, 2009 at 9:50 AM, Jim Crossley wrote: > This surprised me: > >  module English; def say; "yes"; end; end >  module French; def say; "oui"; end; end >  x = Object.new >  x.extend English >  x.say                 # "yes" >  x.extend French >  x.say                 # "oui" >  x.extend English >  x.say                 # "oui" > > What wrong assumptions am I making that this surprises me? Matz has already explained that module inclusion is a one-time only deal. Here's a bit on why that is. http://talklikeaduck.denhaven2.com/2007/11/03/a-chat-with-matz-classs-variable-reversion-and-a-mystery-explained >  What is > the more elegant "Ruby way" of alternating an object's behavior at > runtime? I'd use a form of delegation module English; def self.agree; "yes"; end; end module French; def self.agree; "oui"; end; end class Speaker attr_accessor :language def initialize(language = English) self.language = language end def say language.agree end def speak(language) self.language = language end end jack = Speaker.new jacques = Speaker.new(French) jack.say # => "yes" jacques.say # => "oui" jack.speak(French) jacques.speak(English) jack.say # => "oui" jacques.say # => "yes" jack.speak(English) jacques.speak(French) jack.say # => "yes" jacques.say # => "oui" -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale