From: Robert Klemme Date: 2009-10-27T17:35:31+09:00 Subject: Re: Array#collect in a method call, not working for me Please do not top post. 2009/10/26 Michael Randall : > OK, I *thought* that part was working, but now I see that it wasn't > really. So to help me understand I wrote the following, to see what it > does and I see that adding the #inspect will give me the string to > compare against. > > But does that mean that (a = [1, 2].class) is setting a to be an Array? > Oh, and thank you! > > Here is my test... > > irb(main):034:0* def proovy( n ) > irb(main):035:1>   a = n.class.inspect > irb(main):036:1>   b = n.class > irb(main):037:1>   puts "a: #{a}" > irb(main):038:1>   puts "b: #{b}" > irb(main):039:1>   case a > irb(main):040:2>     when "Array"  : puts "a matched Array in case" > irb(main):041:2>     when "Fixnum" : puts "a matched Fixnum in case" > irb(main):042:2>   end > irb(main):043:1>   case b > irb(main):044:2>     when "Array"  : puts "b matched Array in case" > irb(main):045:2>     when "Fixnum" : puts "b matched Fixnum in case" > irb(main):046:2>   end > irb(main):047:1> end Note that you can simplify the test: irb(main):004:0> [[], "foo"].each {|obj| case obj irb(main):005:2> when Array irb(main):006:2> printf "%p is an array\n", obj irb(main):007:2> when String irb(main):008:2> printf "%p is a string\n", obj irb(main):009:2> else irb(main):010:2* printf "i don't know what %p is.\n", obj irb(main):011:2> end} [] is an array "foo" is a string => [[], "foo"] case uses the === operator: irb(main):012:0> Array === [1,2,3] => true irb(main):013:0> Array === "foo" => false irb(main):014:0> String === "foo" => true IMHO testing against the class is superior to testing against the type's name. Here's why: in case of inheritance the name test will fail while the class test still succeeds irb(main):016:0> class FooArray < Array; end => nil irb(main):017:0> Array === FooArray.new => true irb(main):018:0> "Array" === FooArray.name => false Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/