Last Updated: February 25, 2016
·
868
· heroic

Ruby case ... when

When using case ... when in ruby it is important to note the way how classes are compared

1 === 1
 => true
Fixnum === Fixnum
 => false

So

obj = 'hello'
case obj.class
when String
  print('It is a string')
when Fixnum
  print('It is a number')
else
  print('It is not a string')
end

Will print "It is not a string".

However,

obj = 'hello'
case obj  # was case obj.class
when String
  print('It is a string')
when Fixnum
  print('It is a number')
else
  print('It is not a string')
end

Will work the way we expect it to.

This is because the === operator has been defined so that it returns true if you apply it over a class and an instance of that class.

1 Response
Add your response

Interesting :) thanks!

over 1 year ago ·