From: Michael Granger Date: 2003-09-12T06:38:10+09:00 Subject: Re: Passing an Object Class from a method to a caller RLMuller writes: > I can't seem to pass an Object Class from a method to a calling routine > > Here's what I wrote: > > def getTypeOf(o) > aTypes = [Array, String, Numeric, Fixnum, Struct, MatchData] > result = Object > i = 0 > for t in aTypes > i += 1 > if o.is_a?t then > result=t > print "Index = #{i.to_s}: Type = '#{t.to_s}'\n" > break > end > result > end > end > > obj = "abc" > print "Type of object '#{obj.to_s}' is '#{getTypeOf(obj).to_s}'\n\n}" This happens because your break causes the value of the last evaluated statement (i.e., the 'print') to be the result of the 'for' loop, which is what it breaks out of. You could change it to 'break result' if you're using 1.8; for a way of doing the same thing in a more Ruby-ish manner (IMHO), what about this: Types = [Array, String, Numeric, Fixnum, Struct, MatchData] def getTypeOf( o ) t = Types.find {|type| o.is_a?( type )} || Object i = Types.index( t ) print "Index = #{i}: Type = '#{t}'\n" return t end [ "abc", 14, 6.8, :foo, /\w/.match("foo") ].each {|obj| print "Type of object %p is '%s'\n\n" % [ obj, getTypeOf(obj) ] } # Results in: # # Index = 1: Type = 'String' # Type of object "abc" is 'String' # # Index = 2: Type = 'Numeric' # Type of object 14 is 'Numeric' # # Index = 2: Type = 'Numeric' # Type of object 6.8 is 'Numeric' # # Index = : Type = 'Object' # Type of object :foo is 'Object' # # Index = 5: Type = 'MatchData' # Type of object # is 'MatchData' # Note also that because all 'Fixnum' objects are also 'Numeric' objects, #getTypeOf will never return 'Fixnum'. -- Michael Granger Rubymage, Believer, Architect The FaerieMUD Consortium