From: Xeno Campanoli Date: 2010-01-21T04:05:39+09:00 Subject: Re: Looking for object.inherits?(Classname) Robert Klemme wrote: > 2010/1/20 Xeno Campanoli : >> I'm looking for a way to make sure an object being passed is in some class >> family, or to say it otherwise, inherits some specific class, but not >> necessarily directly. In fact, it could be a great-great-grandparent class, >> and that would be okay, and needs to be okay. Is there something where I >> can take an object and go >> >> unless object.inherits?(MyClass) >> raise SyntaxError, "etc." >> end > > First of all that would not be a SyntaxError because the syntax is not > affected. Using this error type will create misleading error > messages. If I want a method that only takes objects of family Xclass, and I get one passed that is not in that family, isn't that a syntax error? Bad type passed in that argument place? What's the difference between that and passing a string when it needs say an array? > > Here are all the ways that I am aware of (trying to summarize what > others have posted so far): > > irb(main):010:0> a = [] > => [] > irb(main):011:0> a.class.ancestors > => [Array, Enumerable, Object, Kernel, BasicObject] > irb(main):012:0> a.class.ancestors.include? Enumerable > => true > irb(main):013:0> a.kind_of? Enumerable > => true > irb(main):014:0> a.is_a? Enumerable > => true > irb(main):015:0> Enumerable === a > => true > irb(main):016:0> > > Note that I do not recommend using the test from line 12 as it is > likely much more inefficient than the other ones. The test from line > 15 is especially suited for use with "case" statements as in Thank you. That is the kind of answer I really needed. Sincerely, Xeno > > case a > when Enumerable > puts "it's enumerable" > when Array, Hash > puts "It's a special enumerable" > when Integer > puts "You can count on me." > else > puts "No idea about a." > end > > Another note: more often than not it is not necessary to test for the > type of an object. You rather invoke those methods on it that you > expect it to implement. You will get an exception anyway if the > object does not implement the method (NoMethodError). You can find > more details about this concept under the label "duck typing", e.g. > http://en.wikipedia.org/wiki/Duck_typing > > Kind regards > > robert > -- Harping Statements about Harry Reid's Comments make profusely corrupt and racist staff at Fox News feel somehow a little less evil looking than they in fact are.