Surprising behavior when extending instances

J

Jim Crossley

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? What is
the more elegant "Ruby way" of alternating an object's behavior at
runtime?

Thanks,
Jim
 
R

Rick DeNatale

This surprised me:

=A0module English; def say; "yes"; end; end
=A0module French; def say; "oui"; end; end
=A0x =3D Object.new
=A0x.extend English
=A0x.say =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 # "yes"
=A0x.extend French
=A0x.say =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 # "oui"
=A0x.extend English
=A0x.say =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 # "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-varia=
ble-reversion-and-a-mystery-explained
=A0What 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 =3D English)
self.language =3D language
end

def say
language.agree
end

def speak(language)
self.language =3D language
end
end

jack =3D Speaker.new
jacques =3D Speaker.new(French)

jack.say # =3D> "yes"
jacques.say # =3D> "oui"

jack.speak(French)
jacques.speak(English)

jack.say # =3D> "oui"
jacques.say # =3D> "yes"

jack.speak(English)
jacques.speak(French)

jack.say # =3D> "yes"
jacques.say # =3D> "oui"





--=20
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top