From: Robert Klemme Date: 2008-03-21T20:09:56+09:00 Subject: Re: including instance methods and setting an instance varia On 21.03.2008 11:15, Leon Bogaert wrote: > Can I "connect" with the instance if it get's instanciated? Because I > wanted to do something like: > > if not self.respond_to? :each > return false > end The bit above can be shortened to return false unless respond_to? :each There are at least these three options: 1. do not check at all This is my preferred solution, as it is the simplest and works well. irb(main):001:0> class Foo irb(main):002:1> include Enumerable irb(main):003:1> end => Foo irb(main):004:0> f=Foo.new => # irb(main):005:0> f.map {|x| x+1} NoMethodError: undefined method `each' for # from (irb):5:in `map' from (irb):5 from :0 2. check on the class level, this should generally be sufficient irb(main):001:0> module Checker irb(main):002:1> def self.included(cl) irb(main):003:2> cl.instance_method :each irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> class Baz irb(main):007:1> include Checker irb(main):008:1> end NameError: undefined method `each' for class `Baz' from (irb):3:in `instance_method' from (irb):3:in `included' from (irb):7:in `include' from (irb):7 from :0 irb(main):009:0> Baz => Baz irb(main):010:0> Baz.ancestors => [Baz, Checker, Object, Kernel] irb(main):011:0> Note that even the exception does not prevent inclusion. But you can react on this and define the method for example. 3. on instantiation, in this case you need to be in the inheritance chain irb(main):001:0> module Checker irb(main):002:1> def initialize(*a,&b) irb(main):003:2> method :each irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> class Foo irb(main):007:1> include Checker irb(main):008:1> def initialize irb(main):009:2> super irb(main):010:2> end irb(main):011:1> end => nil irb(main):012:0> Foo.new NameError: undefined method `each' for class `Foo' from (irb):3:in `method' from (irb):3:in `initialize' from (irb):9:in `initialize' from (irb):12:in `new' from (irb):12 from :0 irb(main):013:0> 4. check when individual objects are extended irb(main):001:0> module Checker irb(main):002:1> def self.extended(o) irb(main):003:2> o.method :each irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> x = Object.new => # irb(main):007:0> x.extend Checker NameError: undefined method `each' for class `Object' from (irb):3:in `method' from (irb):3:in `extended' from (irb):7:in `extend' from (irb):7 from :0 irb(main):008:0> Kind regards robert