From: Brian Candler Date: 2012-04-19T02:46:48+09:00 Subject: Re: Why must I know whether I extend a class or a module? Marc Heiler wrote in post #1057208: > Hi. > > I have one module and one class. > > module Foo > def test > puts 'This is method test() from module Foo.' > end > end > > class Bar > def test > puts 'This is method test() from class Bar.' > end > end > > > If I want to modify that at a later time, I need > to do something like: > > module Foo > def test > puts 'Yes, still testing'. > end > end > > Or > > class Bar > # etc.. > > My question is: > > - Why do I need to KNOW that it is a module or a class? > > Can't I simply say "I do not care what it is a class or a module, simply > add this method to it."? Yes you can: >> class Foo; end => nil >> module Bar; end => nil >> Foo.module_eval { def xxx; puts "xxx"; end } => nil >> Bar.module_eval { def yyy; puts "yyy"; end } => nil >> Foo.new.xxx xxx => nil >> Object.new.extend(Bar).yyy yyy => nil Note that module_eval and class_eval both exist, but I have not been able to find a case where they behave differently; as far as I know they are interchangeable. > I don't understand why I need to explicitely know that one is a module > and the other is a class. I guess it's just a syntax choice, and a safety feature - you don't accidentally add methods to a module when you meant a class, or vice versa. After all, when you write module Foo ... then you are talking about a single thing, "Foo", so you almost certainly know what kind of thing it is. If you want to do it dynamically (e.g. the module or class is in a variable) then you need a different syntax anyway: var = Foo var.module_eval { ... } or: var = :Foo m = Object.const_get(var) m.module_eval { ... } Regards, Brian. -- Posted via http://www.ruby-forum.com/.