LAMBEAU Bernard
4/7/2009 3:21:00 PM
Because the =3D=3D=3D operator of the Class class (used in case statements)
checks for 'is an instance of'.
So, the following:
> case klass
> when String
> puts "String!"
> end
is to be interpreted as String=3D=3D=3Dklass, that is to,
klass.is_a?(String), which is false. But the following is true:
case klass
when Class
puts 'It's a class of course'
end
Hope it helps
blambeau
On Tue, Apr 7, 2009 at 5:10 PM, Eric Will <rakaur@malkier.net> wrote:
> I've encountered this in the past and thought I was messing something
> up, but it's happening still.
>
> Can anyone tell me why this:
>
> puts "ruby-#{RUBY_VERSION} [#{RUBY_PLATFORM}]"
>
> [String, Array, Hash].each do |klass|
> =A0 =A0case klass
> =A0 =A0when String
> =A0 =A0 =A0 =A0puts "String!"
> =A0 =A0when Array
> =A0 =A0 =A0 =A0puts "Array!"
> =A0 =A0when Hash
> =A0 =A0 =A0 =A0puts "Hash!"
> =A0 =A0else
> =A0 =A0 =A0 =A0puts "I don't know: #{klass}"
> =A0 =A0end
> end
>
> Produces this:
>
> ruby-1.8.7 [x86_64-linux]
> I don't know: String
> I don't know: Array
> I don't know: Hash
>
> ruby-1.9.1 [x86_64-linux]
> I don't know: String
> I don't know: Array
> I don't know: Hash
>
> Am I missing something here? In order to get the expected result I
> have to do this:
>
> [String, Array, Hash].each do |klass|
> =A0 =A0case klass.to_s
> =A0 =A0when "String"
> =A0 =A0 =A0 =A0puts "String!"
> =A0 =A0when "Array"
> =A0 =A0 =A0 =A0puts "Array!"
> =A0 =A0when "Hash"
> =A0 =A0 =A0 =A0puts "Hash!"
> =A0 =A0else
> =A0 =A0 =A0 =A0puts "I don't know: #{klass}"
> =A0 =A0end
> end
>
> This works of course, but why doesn't the former? I find it hard to
> believe this has been overlooked. What am I missing?
>
> -- Eric Will
>
>