Ruby Gotcha Using case to Compare Classes

I was working on some code today that makes use of the activerecord-activesalesforce gem to connect to SalesForce and pull records for processing in my rails app. I needed to handle some types of records differently than others, so I decided to use a case statement to process the different SalesForce records accordingly.

I ran into a problem comparing classes, my code looked something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
[Array, String, Integer].each do |klass|
  case klass
  when Array
    puts "Array here!"
  else
    puts "No Array here."
  end
end
 
# Resulted In
# No Array Here.
# No Array Here.
# No Array Here.

Not exactly what I expected. Luckily, my genius rock-star-programmer pair realized that Ruby’s case must be using = rather than .

Changing the code to the following solved my problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
[Array, String, Integer].each do |klass|
  case klass
  when klass == Array
    puts "Array here!"
  else
    puts "No Array here."
  end
end
 
# Results
# Array here!
# No Array here.
# No Array here.

Next up is figuring out why === behaves like this when comparing classes.

1
2
3
4
Array === Array #false
Array == Array #true
 
#why?

Speak Your Mind

*