From: Daniel Schierbeck Date: 2006-07-29T03:35:04+09:00 Subject: Re: Weird problem with case expressions ara.t.howard@noaa.gov wrote: > On Sat, 29 Jul 2006, Daniel Schierbeck wrote: > >>> althogh i personally would use >>> >>> [Integer, String, Array].detect{|c| c === 'foo'} >>> >>> since i can easily become a one liner, even with many classes. if >>> you need >>> the string then >>> >>> [Integer, String, Array].detect{|c| c === 'foo' and c.name.downcase} >> >> That would work, but I don't think classes and types are always the >> same. An >> ordered hash is still a hash, even if it doesn't descend from Hash. This >> way, all objects that respond to #to_hash is in some way a hash, and I >> can >> trust (to some degree) that the object returned when calling that method >> implements the interface of Hash. > > indeed. still, the technique is more compact than a case: > > %w( to_int to_str to_hash to_ary ).detect{|m| 'foo'.respond_to? m} Very nice solution! It could even be written as: %w{int str ary}.detect{|type| obj.respond_to? "to_#{type}"} the only problem is that it violates DRY when used in case expressions: case [:int, :str, :ary].detect{|type| obj.respond_to? "to_#{type}"} when :int then "integer" when :str then "string" when :ary then "array" end (note that this isn't about mapping "ary" to "array" -- it's about determining the type of an object, and behave in accordance with that.) Cheers, Daniel